gpt4 book ai didi

javascript - 返回新的 Promise 和 Promise.resolve 的区别

转载 作者:行者123 更新时间:2023-12-01 15:03:36 25 4
gpt4 key购买 nike

对于下面的代码片段,我想了解 NodeJS 运行时如何处理事情:

const billion = 1000000000;

function longRunningTask(){
let i = 0;
while (i <= billion) i++;

console.log(`Billion loops done.`);
}

function longRunningTaskProm(){
return new Promise((resolve, reject) => {
let i = 0;
while (i <= billion) i++;

resolve(`Billion loops done : with promise.`);
});
}

function longRunningTaskPromResolve(){
return Promise.resolve().then(v => {
let i = 0;
while (i <= billion) i++;

return `Billion loops done : with promise.resolve`;
})
}


console.log(`*** STARTING ***`);

console.log(`1> Long Running Task`);
longRunningTask();

console.log(`2> Long Running Task that returns promise`);
longRunningTaskProm().then(console.log);

console.log(`3> Long Running Task that returns promise.resolve`);
longRunningTaskPromResolve().then(console.log);

console.log(`*** COMPLETED ***`);

第一种方法:

longRunningTask() function will block the main thread, as expected.



第二种方法:

In longRunningTaskProm() wrapping the same code in a Promise, was expecting execution will move away from main thread and run as a micro-task. Doesn't seem so, would like to understand what's happening behind the scenes.



第三种方法:

Third approach longRunningTaskPromResolve() works.



这是我的理解:

Creation and execution of a Promise is still hooked to the main thread. Only Promise resolved execution is moved as a micro-task.



我有点不相信我发现的任何资源和我的理解。

最佳答案

所有这三个选项都在主线程中运行代码并阻止事件循环。当他们开始运行 while 时,时间略有不同。循环代码以及它们何时阻塞事件循环,这将导致它们与某些控制台消息的运行时间不同。

第一个和第二个选项立即阻止事件循环。

第三个选项阻止事件循环从下一个滴答开始 - 那是 Promise.resolve().then()调用您传递给 .then() 的回调(在下一个刻度)。

第一个选项只是纯同步代码。毫不奇怪,它会立即阻塞事件循环,直到 while循环完成。

在第二个选项中,新的 Promise 执行器回调函数也被同步调用,因此它再次立即阻塞事件循环,直到 while循环完成。

在第三个选项中,它调用:

Promise.resolve().then(yourCallback);
Promise.resolve()创建一个已经解决的 promise ,然后调用 .then(yourCallback)在那个新的 promise 上。此日程安排 yourCallback在事件循环的下一个滴答上运行。根据 promise 规范, .then()处理程序总是在事件循环的 future 滴答上运行,即使 promise 已经解决。

同时,在此之后的任何其他 Javascript 都会继续运行,并且只有当该 Javascript 完成后,解释器才会进入事件循环的下一个滴答声并运行 yourCallback .但是,当它确实运行该回调时,它会在主线程中运行,因此会阻塞直到它完成。

Creation and execution of a Promise is still hooked to the main thread. Only Promise resolved execution is moved as a micro-task.



示例中的所有代码都在主线程中运行。一个 .then()处理程序计划在事件循环的 future 滴答中运行(仍在主线程中)。这种调度使用了一个微任务队列,它允许它在事件队列中的其他一些东西之前得到它,但它仍然在主线程中运行并且它仍然在事件循环的 future 滴答上运行。

此外,“履行 promise ”这个词有点用词不当。 Promises 是一个通知系统,您可以使用 .then() 计划在将来的某个时间使用它们运行回调。或 .catch().finally()在一个 promise 上。因此,一般而言,您不想考虑“执行 promise ”。您的代码执行导致创建一个 promise ,然后您注册该 promise 上的回调以根据该 promise 发生的情况在 future 运行。 Promises 是一个专门的事件通知系统。

Promise 有助于在事情完成时通知您或帮助您安排事情何时进行。他们不会将任务移动到另一个线程。

作为说明,您可以插入 setTimeout(fn, 1)在第三个选项之后,看到超时被阻止运行,直到第三个选项完成。这是一个例子。而且,我已将阻塞循环全部设为 1000 毫秒长,以便您可以更轻松地看到。在这里在浏览器中运行它或复制到 node.js 文件并在那里运行它以查看 setTimeout()longRunningTaskPromResolve() 的执行时间阻止按时执行.所以, longRunningTaskPromResolve()还在堵。将其放入 .then()处理程序在运行时会发生变化,但它仍然处于阻塞状态。

const loopTime = 1000;

let startTime;
function log(...args) {
if (!startTime) {
startTime = Date.now();
}
let delta = (Date.now() - startTime) / 1000;
args.unshift(delta.toFixed(3) + ":");
console.log(...args);
}

function longRunningTask(){
log('longRunningTask() starting');
let start = Date.now();
while (Date.now() - start < loopTime) {}

log('** longRunningTask() done **');
}

function longRunningTaskProm(){
log('longRunningTaskProm() starting');
return new Promise((resolve, reject) => {
let start = Date.now();
while (Date.now() - start < loopTime) {}
log('About to call resolve() in longRunningTaskProm()');
resolve('** longRunningTaskProm().then(handler) called **');
});
}

function longRunningTaskPromResolve(){
log('longRunningTaskPromResolve() starting');
return Promise.resolve().then(v => {
log('Start running .then() handler in longRunningTaskPromResolve()');
let start = Date.now();
while (Date.now() - start < loopTime) {}
log('About to return from .then() in longRunningTaskPromResolve()');
return '** longRunningTaskPromResolve().then(handler) called **';
})
}


log('*** STARTING ***');

longRunningTask();

longRunningTaskProm().then(log);

longRunningTaskPromResolve().then(log);

log('Scheduling 1ms setTimeout')
setTimeout(() => {
log('1ms setTimeout Got to Run');
}, 1);

log('*** First sequence of code completed, returning to event loop ***');


如果您运行此代码段并查看每条消息的确切输出时间以及与每条消息关联的时间,您就可以看到事情开始运行的确切顺序。

这是我在 node.js 中运行它时的输出(添加行号以帮助解释下面的解释):
1    0.000: *** STARTING ***
2 0.005: longRunningTask() starting
3 1.006: ** longRunningTask() done **
4 1.006: longRunningTaskProm() starting
5 2.007: About to call resolve() in longRunningTaskProm()
6 2.007: longRunningTaskPromResolve() starting
7 2.008: Scheduling 1ms setTimeout
8 2.009: *** First sequence of code completed, returning to event loop ***
9 2.010: ** longRunningTaskProm().then(handler) called **
10 2.010: Start running .then() handler in longRunningTaskPromResolve()
11 3.010: About to return from .then() in longRunningTaskPromResolve()
12 3.010: ** longRunningTaskPromResolve().then(handler) called **
13 3.012: 1ms setTimeout Got to Run

这是一个分步注释:
  • 事情开始。
  • longRunningTask()发起。
  • longRunningTask()完成。它是完全同步的。
  • longRunningTaskProm()发起。
  • longRunningTaskProm()电话resolve() .从中可以看出promise executor函数(传递给new Promise(fn)`的回调也是完全同步的。
  • longRunningTaskPromResolve()发起。您可以看到来自 longRunningTaskProm().then(handler) 的处理程序还没有被调用。它已被安排在事件循环的下一个滴答上运行,但由于我们还没有回到事件循环,因此还没有被调用。
  • 我们现在正在设置 1ms 计时器。请注意,此计时器仅在我们启动后 1 毫秒设置 longRunningTaskPromResolve() .那是因为 longRunningTaskPromResolve()还没有做太多。它跑了 Promise.resolve().then(handler) ,但所做的只是安排了 handler在事件循环的 future 滴答上运行。所以,只用了 1 毫秒来安排它。该函数的长时间运行部分尚未开始运行。
  • 我们到达这一系列代码的末尾并返回到事件循环。
  • 下一个计划在事件循环中运行的是来自 longRunningTaskProm().then(handler) 的处理程序。这样就被调用了。您可以看到它已经在等待运行,因为它在我们返回到事件循环后仅运行了 1 毫秒。该处理程序运行,我们返回到事件循环。
  • 下一个计划在事件循环中运行的是来自 Promise.resolve().then(handler) 的处理程序。所以我们现在看到它开始运行,因为它已经排队,它在前一个事件完成后立即运行。
  • longRunningTaskPromResolve() 中的循环正好需要 1000 毫秒运行然后它从它的 .then() 返回然后调度下一个的处理程序 .then()该 promise 链中的处理程序在 eventl 循环的下一个滴答上运行。
  • 那个.then()得到运行。
  • 然后,终于当没有.then()计划运行的处理程序,setTimeout()回调开始运行。它被设置为在 1 毫秒内运行,但它被所有以更高优先级运行的 promise 操作延迟了,所以它没有运行 1 毫秒,而是在 1004 毫秒内运行。
  • 关于javascript - 返回新的 Promise 和 Promise.resolve 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61637464/

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