Async / Await in IIFF ( 立即执行函数 )

预期以下代码应该打印顺序会是 1 2 3 4 5 但实际执行时却是 1 2 5 3 4

(async () => {
  console.log("1");
  let n = await new Promise((reslove, reject) => {
    console.log("2");
    setTimeout(() => {
      reslove("3");
    }, 2000);
  });
  console.log(n);
  console.log("4");
})();

console.log("5");

预计 await new Promise 应该是会等到 reslove("3"); 执行后再顺序执行,怎麽就直接跳过了呢? 若是想要 1 2 3 4 5 的执行该怎麽调整?

附注
.babelrc

{
  "presets": [
    [
      "env",
      {
        "targets": {
          "node": "current"
        }
      }
    ]
  ],
  "plugins": ["transform-object-rest-spread"],
  "ignore": ["node_modules"]
}
阅读 14.5k
4 个回答

setTimeout 是一个 macrotask,所以会先输出1 2 5,到下一个event loop,setTimeout才会resolve 3出去,然后才会 log 4

(async () => {
  console.log("1");
  let n = await new Promise((reslove, reject) => {
    console.log("2");
    setTimeout(() => {
      reslove("3");
    }, 2000);
  });
  console.log(n);
  console.log("4");
  console.log("5");
})();

async/await是以同步的方式去写异步代码。你到2之后执行的是setTimeout(),这是一个异步,后续的n和4都要等到resolve之后才能够执行。

setTimeout(() => {
    console.log(2)
}, 1000)
console.log(1)

执行顺序为1 2

和上面的是类似的,自执行函数中,到了setTimeout()就是一个异步,后续都要等待resolve,自执行函数“暂停了”,之后执行的就是5了,然后等待resolve,输出3,4

有错误欢迎指出~共同学习

(async() => {
    console.log("1");
    let n = await new Promise((reslove, reject) => {
        console.log("2");
        setTimeout(() => {
            reslove("3");
        }, 2000);
    });
    console.log(n);
    console.log("4");
})().then(()=>{
    console.log("5");
});

代码改成这样你应该就能理解了,因为async function是一个Promise。虽然写着await,但并不代表CPU就阻塞了。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题