承诺的奇怪行为

Weird behavior with promises

我正在用 promises 做一些测试,但我写的代码与我预期的不一样:

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 中)。您的代码永远不会被抢占,代码从开始到结束总是 运行 秒,并且以后只能 "register" 为平台代码 运行。

promise 构造函数 运行 是同步的。 Promises 不会在您的代码中引入线程,它们只会将 then 回调中的 运行ning 代码延迟到 "after all synchronous code" 但在所有平台代码之前。

Promises 只是未来值的句柄 - 它们不会让您的代码在另一个线程上执行。如果您需要 运行 在另一个线程上编写代码,您需要使用 worker_threads(在 Node.js 中)或浏览器中的网络工作者。

问题是您的承诺不包含任何异步代码。 如果您不想等待 function1 的承诺中的代码被执行,您需要编写它,例如在 setTimeout 中。

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

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

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

function3();