zxdfe / FE-Interview

Every step counts
34 stars 1 forks source link

第70题:promise-async笔试题,写出代码的运行结果, 并解释原因? #71

Open zxdfe opened 2 years ago

zxdfe commented 2 years ago
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');
zxdfe commented 2 years ago
async function async1() {
    // 4. 同步执行
    console.log('async1 start');
    // 5. 同步执行 async2 
    await async2(); // => console.log(async2)
    console.log('async1 end'); // 6.await后面的放到微任务队列中 微任务1
}
async function async2() {
    console.log('async2');
}
// 1. 同步执行
console.log('script start');
setTimeout(function() {
  // 2. 遇到宏任务,将回调放到宏任务队列等待 宏任务1
    console.log('setTimeout');
}, 0)
// 3. 同步执行async1 , 进入async1 
async1();
new Promise(function(resolve) {
  // 7. 回过来同步执行 new Promise内部的代码,同步!
    console.log('promise1');
    resolve();
}).then(function() {
    // 8. 放到微任务对象中 微任务2
    console.log('promise2');
});
// 9. 同步执行 ==> 执行完后,再先依次清空微任务队列,再执行宏任务队列中的setTimeout
console.log('script end');
2734209032 commented 1 year ago

1.script start 2.async1 start 3.async2 4.promise1 5.script end 6.async1 end 7.promise2 8.settimeout