轉自:https://juejin.im/post/5c0397186fb9a049b5068e54
1、題目一
async function async1(){ console.log('async1 start') await async2() console.log('async1 end') } async function async2(){ console.log('async2') } console.log('script start') setTimeout(function(){ console.log('setTimeout') },0) async1(); new Promise(function(resolve){ console.log('promise1') resolve(); }).then(function(){ console.log('promise2') }) console.log('script end')
2、題目二:
async function async1(){ console.log('async1 start') await async2() console.log('async1 end') } function async2(){ // 去掉了 async 關鍵字
console.log('async2'); } console.log('script start') setTimeout(function(){ console.log('setTimeout') },0) async1(); new Promise(function(resolve){ console.log('promise1') resolve(); }).then(function(){ console.log('promise2') }) console.log('script end')
需要說明的是:
正常情況下,await
命令后面是一個 Promise 對象,返回該對象的結果。如果不是 Promise 對象,就直接返回對應的值(相當於直接Promise.resolve)。
例子:
async function f() { // 等同於
// return 123;
return await 123; } f().then(v => console.log(v)) // 123
上面代碼中,await
命令的參數是數值123
,這時等同於return 123
。