javascript - 有没有办法让这个顶级代码同步
问题描述
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
那可能吗?
解决方案
首先,您应该返回 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.');
})
推荐阅读
- docker - docker-compose 无法连接到 docker 守护进程?
- c++11 - GCC-4 和 GCC-5/6/7/8/9 之间 std::function 的无证 ABI 更改,如何使 .so 与 devtoolset-4/6/7/8/9 一起使用?
- mysql - 如何使用 MYSQL JOIN 链接表?
- docker - 使用 Dockerfile 复制
- java - Search Between 可以隐藏过去的 product_Name 交易
- sql-server - WinSCP 脚本手动工作正常,但在 SQL Server 代理作业执行时失败
- c - 使用 write() 将 char* 从用户输入写入文件
- git - 如何使用其他用户的 ssh 密钥从 jenkins 推送到 master 分支
- sql - 如何在 SQL Server v17.3 中显示 30 分钟的时间间隔计数
- python - 从帖子表单上传文件到谷歌驱动器