js的事件循环机制下,记录一个意外错误
js+

js的事件循环机制下,记录一个意外错误

dylin
2024-06-05 / 0 评论 / 9 阅读 / 正在检测是否收录...

js的事件循环机制是前端的基础概念。下面我们先看两段代码:

setTimeout(()=>{
    console.log("children2")
    Promise.resolve().then(()=>{
        console.log("children3")
    })
},0)
new Promise(function(resolve,reject){
    console.log("children4")
    setTimeout(function(){
        console.log("children5")
        resolve("children6")
    },0)
}).then(res=>{
    console.log("children7")
    setTimeout(function(){
        console.log(res)
    },0)
})
console.log("start")

上面的代码输出:children4、start、children2、children3、children5、children7、children6

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");

上面的代码输出:script start、async1 start、async2、promise1、script end、async1 end、promise2、setTimeout
第二道题时,我出现一个疑惑,当await 后面跟的不是一个 Promise 对象(而是一个同步值或已经解决的 Promise),那么await 后面的代码会被放入微任务队列吗?
验证代码:

async function example() {
    console.log('Start');
    await Promise.resolve(); // 立即解决的 Promise
    console.log('After await');
}

console.log('Before async call');
example();
console.log('After async call start');

// 输出顺序:
// Before async call
// After async call start
// Start
// After await

上面的代码表明:如果 await 后面跟的不是一个异步操作,虽然await 不会真正“等待”任何东西,但它仍然会将后续代码放入微任务队列中。

结论:无论 await 后面跟的是否是一个真正需要等待的异步操作,它都会导致后续代码被放入微任务队列中执行。

0

评论

博主关闭了所有页面的评论