cloudtian / blogs

Summary of knowledge and blogs for every little things
3 stars 0 forks source link

JS中 async await 与 promise执行流程 #45

Open cloudtian opened 3 years ago

cloudtian commented 3 years ago
async function async1() {
    console.log('A async1 start');
    await async2();
    console.log('B async1 end');
}

async function async2 () {
    console.log('C async2');
}

console.log('D script start');

setTimeout(() => {
    console.log('E setTimeout');
}, 0);

async1();

new Promise(function (resolve) {
    console.log('F promise1');
    resolve();
}).then(function () {
    console.log('G promise2');
});

console.log('H script end');
输出
D script start
A async1 start
C async2
F promise1
H script end
B async1 end
G promise2
E setTimeout

说明 Promise()里内容是立即执行的 Promise.then回调内容会被存入到微任务队列中等待执行 setTimeout回调内容会被存入宏任务队列中等待执行 await表达式之后的代码可以被认为是存在在链式调用的then回调中,即加入到微任务队列中