例1
function GenFunc () {
new Promise(function(resolve) {
resolve()
}).then(function() {
console.log('1')
})
console.log('2')
}
GenFunc()
// 执行结果
// 2
// 1
例2
async function GenFunc () {
new Promise(function(resolve) {
resolve()
}).then(function() {
console.log('1')
})
await 'string';
console.log('2')
}
GenFunc()
// 执行结果
// 1
// 2
请问为什么await会改变执行顺序。Promise.then属于microtasks。同步的代码没执行完是不会进入microtasks的。所以请问两段代码结果不一致的原因是什么
async
内的await
会把之后的代码放入新的microtask,即使等待的东西实际上是同步的。详细解析: