javascript - 为什么我的代码不能在 javascript 中异步运行?
问题描述
在我们开始之前,我是一个完全的 JS 初学者。我一直在尝试从主线程上运行繁重的任务,这样程序就不必挂起就可以完成。这是我编写的以下代码。
const tick = Date.now();
const log = (v) => console.log(`${v} \n Elapsed: ${Date.now() - tick}ms`);
const xd = () => {
return Promise.resolve().then(v => {
let i = 0;
while (i < 1000000000) {
i++;
}
return 'done';
})
};
log(' Synchronous 1');
xd().then(log);
log(' Synchronous 2');
let x = 0;
while (x < 1000000000) {
x++;
}
log(' Synchronous 3');
我希望 xd() 在主线程之外运行异步并继续执行下一行代码,并且只有在准备好时才到 console.log。与此同时,我想在主线程上运行相同的 while 循环代码。我测试了其中一个 while 循环个体,在我的计算机上编译大约需要 550 毫秒。从理论上讲,我希望两个循环都以 550 毫秒完成,因为它们是相同的,但是最终需要 1130 毫秒,正好是两倍。为什么 xd() 函数不在后台运行?这是此代码的输出。
Synchronous 1
Elapsed: 0ms
Synchronous 2
Elapsed: 4ms
Synchronous 3
Elapsed: 559ms
done
Elapsed: 1130ms
Process finished with exit code 0
解决方案
推荐阅读
- database-administration - 在greenplum中管理溢出文件
- python - 通过 Anaconda 安装“imputeTS”以在 Python 中使用
- php - 如何更改 mysql 中的事件并更改正在运行的内容
- reactjs - 如何使用 redux 呈现 API 响应并做出反应
- sql - 对用户响应强制超时 SQL Oracle
- mdriven - 如何在 MDriven Turnkey 中设置全局字体
- regex - 如何仅从日志文件中 grep 输入的最后 30 天?
- javascript - 使用jquery将文本添加到输入框
- nginx - 一个用于多个 HTTPS (certbot) 域的 nginx 配置
- kubernetes - 具有特定卷名的 Kubernetes 卷声明待处理