关闭。这个问题需要details or clarity .它目前不接受答案。
想改进这个问题?通过 editing this post 添加详细信息并澄清问题.
2年前关闭。
Improve this question
运行片段并查看它们的持续时间,您会看到第一个片段执行 log('Synchronous 2')
之前 billion loops done
.它花费了 0 毫秒,但第二个片段使用 async 关键字 block log('Synchronous 2')
直到循环结束。
const tick = Date.now();
const log = (v) => console.log(`${v} \n Elapsed: ${Date.now() - tick}ms`);
const notBlocked = () => {
return Promise.resolve().then(() => {
let i = 0;
while(i < 1000000000) { i++; } //runs asynchronically
return '🐷 billion loops done';
})
}
log('🥪 Synchronous 1');
notBlocked().then(log);
log('🥪 Synchronous 2');
日志('同步 2')被阻止
const tick = Date.now();
const log = (v) => console.log(`${v} \n Elapsed: ${Date.now() - tick}ms`);
const notBlocked = async() => {
let i = 0;
while(i < 100000000) { i++; } //runs synchronically and blocks main thread
return '🐷 billion loops done';
}
log('🥪 Synchronous 1');
notBlocked().then(log);
log('🥪 Synchronous 2');
最佳答案
异步函数会同步运行,直到遇到等待,因此如果您的目标是使用异步函数将某些代码作为微任务延迟,您需要在其中插入等待,即使它正在等待一些无用的东西。
const tick = Date.now();
const log = (v) => console.log(`${v} \n Elapsed: ${Date.now() - tick}ms`);
const notBlocked = async () => {
await undefined; // yield until the microtasks run
let i = 0;
while(i < 1000000000) { i++; }
return '🐷 billion loops done';
}
log('🥪 Synchronous 1');
notBlocked().then(log);
log('🥪 Synchronous 2');
关于javascript - 如何为 Promise.resolve().then() 使用异步替代方案?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62820853/