小编Pas*_*cal的帖子

是否需要setTimeout?

我有一个async,await和setTimeout()的问题.我想,我使用异步函数来处理慢进程.所以我尝试了一个大循环.在我的计算机上,运行以下代码需要几秒钟:

function slowFunction() {
    return new Promise(resolve => {
        setTimeout(() => {
            for (let i = 0; i < 4000000000; i++) {};
            resolve('Ready at ' + new Date().toLocaleTimeString('de'));
        }, 0);
    });
};


console.log('Start: ' + new Date().toLocaleTimeString('de'));

(async () => {
    console.log('Call slow function.');
    console.log(await slowFunction());
})();

console.log('There is no need to wait for the slow function: ' + new Date().toLocaleTimeString('de'));
Run Code Online (Sandbox Code Playgroud)

输出是:

Start: 16:39:20
Call slow function.
There is no need to wait for the slow function: 16:39:20
Ready at …
Run Code Online (Sandbox Code Playgroud)

javascript asynchronous settimeout async-await

2
推荐指数
1
解决办法
70
查看次数