首页 > 解决方案 > 为什么我的代码不能在 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

标签: javascriptnode.jsasynchronousasync-await

解决方案


推荐阅读