首页 > 解决方案 > 有没有办法让这个顶级代码同步

问题描述

Codepen 链接:https ://codepen.io/AnirudhMS/pen/poRmjao ?

代码:

console.log('Started script execution.');
(async () => {
  let promiseWrapper = async () => {
    setTimeout(() => {
      console.log("Inside async script.");
      Promise.resolve();
    }, 0);
  };
  await promiseWrapper();
})();
console.log('Finished script execution.');

输出:

Started script execution.
Finished script execution.
Inside async script.

问题:从上面的输出可以看出,在顶级代码中,浏览器不会等待异步操作完成。现在这也意味着dom-ready在同步代码完成执行后将触发类似的事件。问题不在于dom-ready事件,而是有办法确保输出如下:

Started script execution.
Inside async script.
Finished script execution.

编辑: 注意:如果我将 setTimeout 替换为 await Promise 调用,则该解决方案需要工作!!!

编辑 2: 解决方案需要在执行异步脚本后触发dom-ready事件或事件。DOMContentLoaded那可能吗?

标签: javascriptasync-awaitevent-loop

解决方案


首先,您应该返回 Promise,不仅Promise.resolve在超时回调中使用,其次,在顶级范围内使用类似 Promise 的变体:

console.log('Started script execution.');
(async () => {
  let promiseWrapper = () => new Promise((res, rej) => {
    setTimeout(() => {
      console.log("Inside async script.");
      res();
    }, 0);
  });
  await promiseWrapper();
})().then(() => {
  console.log('Finished script execution.');
})

推荐阅读