鍍金池/ 問(wèn)答/網(wǎng)絡(luò)安全  HTML/ async/await 和promise.then 的執(zhí)行時(shí)機(jī)

async/await 和promise.then 的執(zhí)行時(shí)機(jī)

例1
function  GenFunc () {
  new Promise(function(resolve) {
        resolve()
    }).then(function() {
        console.log('1')
    })
  console.log('2')
}
GenFunc()
// 執(zhí)行結(jié)果
// 2
// 1
例2
async function  GenFunc () {
  new Promise(function(resolve) {
        resolve()
    }).then(function() {
        console.log('1')
    })
    await 'string';
    console.log('2')
}
GenFunc()
// 執(zhí)行結(jié)果
// 1
// 2

請(qǐng)問(wèn)為什么await會(huì)改變執(zhí)行順序。Promise.then屬于microtasks。同步的代碼沒(méi)執(zhí)行完是不會(huì)進(jìn)入microtasks的。所以請(qǐng)問(wèn)兩段代碼結(jié)果不一致的原因是什么

回答
編輯回答
柒槿年
既然題主自己提到了microtask,我就假設(shè)題主已經(jīng)知道例1是怎么回事了

async內(nèi)的await會(huì)把之后的代碼放入新的microtask,即使等待的東西實(shí)際上是同步的


詳細(xì)解析:

(async function GenFunc() {
  new Promise(function constructPromise(resolve) { // 1. Promise構(gòu)造器,同步執(zhí)行constructPromise
    resolve()                                      // 2. resolve,將promiseCallback放入microtask隊(duì)列位置1
  }).then(function promiseCallback() {
    console.log('1')                               // 6. microtask隊(duì)列位置1
  })
  await 'string'                                   // 3. await,將之后的所有代碼放入microtask隊(duì)列位置2
  console.log('2')                                 // 7. microtask隊(duì)列位置2
})()                                               // 4. async call return,返回Promise<pending>
console.log('3')                                   // 5. 執(zhí)行剩余的同步代碼
2017年5月20日 16:13