轉自:http://www.javashuo.com/article/p-rqhtpwqh-gt.htmlpromise
一、題目一async
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')
二、題目二:post
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')
須要說明的是:spa
正常狀況下,await
命令後面是一個 Promise 對象,返回該對象的結果。若是不是 Promise 對象,就直接返回對應的值(至關於直接Promise.resolve)。code
例子:對象
async function f() { // 等同於
// return 123;
return await 123; } f().then(v => console.log(v)) // 123
上面代碼中,await
命令的參數是數值123
,這時等同於return 123
。blog