gpt4 book ai didi

javascript - 带有 promise 的奇怪行为

转载 作者:行者123 更新时间:2023-11-29 16:31:33 26 4
gpt4 key购买 nike

我正在使用 Promise 进行一些测试,但我编写的代码的行为并不完全符合我的预期:

function function1() {
return new Promise((resolve, reject) => {
let i = 5000000000;
while (i > 0) {
i--;
}
resolve("print function1!!!");
});
}

function function2() {
console.log("print function2!!!");
}

function function3() {
function1().then(data => console.log(data));
function2();
}

function3();

这段代码的执行等待function1中的循环完成然后打印:

print function2!!!

print function1!!!

我期望代码会打印“print function2!!!”然后等待循环完成然后打印“print function1!!!”。

为什么 Promise 内的循环会阻塞代码的执行?

最佳答案

Why the loop inside the promise is blocking the execution of the code?

这就是 JavaScript 执行模型(在浏览器和 Node 中)。您的代码永远不会被抢占,代码始终从头到尾运行,并且只能“注册”代码以供平台稍后运行。

Promise 构造函数同步运行。 Promise 不会在代码中引入线程,它们只会将 then 回调中的运行代码推迟到“在所有同步代码之后”但在所有平台代码之前。

Promise 只是 future 值的句柄 - 它们不会使您的代码在另一个线程上执行。如果您需要在另一个线程上运行代码,则需要使用 worker_threads (在 Node.js 中)或浏览器中的 Web Worker。

关于javascript - 带有 promise 的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55868053/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com