承诺构造函数回调的身体何时执行?

发布于 2025-01-23 19:51:54 字数 330 浏览 1 评论 0原文

假设我有以下代码构建Promise

function doSomethingAsynchronous() {
  return new Promise((resolve) => {
    const result = doSomeWork();

    setTimeout(() => {
      resolve(result);
   }), 100);
  });
}

在哪个时间点为Dosomework()调用?是在构建 之后还是立即构建?如果没有,我需要明确需要做些其他事情以确保运行回调吗?

Suppose I have the following code constructing a Promise:

function doSomethingAsynchronous() {
  return new Promise((resolve) => {
    const result = doSomeWork();

    setTimeout(() => {
      resolve(result);
   }), 100);
  });
}

At which point in time is doSomeWork() called? Is it immediately after or as the Promise is constructed? If not, is there something additional I need to do explicitly to make sure the callback is run?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

梦在深巷 2025-01-30 19:51:54

是的,是通过规范同步称为。

来自

executorresolvefuncrecept> requavefunc用作参数。

这是在ecmascript规范中定义的(当然,很难阅读...)此处(在此编辑时,step  9,表明执行者被同步称为):

  1. 让完成完成(呼叫(executor,undefined,«solisolvingFunctions。[[lesolve]],解决方案。[[[recize]]»)»))。
  2. )。

(我的重点)

此保证可能很重要,例如,当您准备多个承诺时,您将全部或race您的执行者具有同步的副作用。

It is called synchronously, yes, by specification.

From the MDN:

The executor is called synchronously (as soon as the Promise is constructed) with the resolveFunc and rejectFunc functions as arguments.

This is defined in the ECMAScript specification (of course, it's harder to read...) here (Step 9 as of this edit, showing that the executor is called synchronously):

  1. Let completion be Completion(Call(executor, undefined, « resolvingFunctions.[[Resolve]], resolvingFunctions.[[Reject]] »)).

(my emphasis)

This guarantee may be important, for example when you're preparing several promises you then pass to all or race, or when your executors have synchronous side effects.

浅唱ヾ落雨殇 2025-01-30 19:51:54

您可以通过将同步代码放入体内而不是异步来立即在下面看到身体:

function doSomethingAsynchronous() {
  return new Promise((resolve) => {
    console.log("a");
    resolve("promise result");
  });
}
doSomethingAsynchronous();
console.log("b");

结果显示了立即执行承诺的主体(在打印'B'之前)。

保留承诺的结果,将释放到“然后”调用:

function doSomethingAsynchronous() {
  return new Promise((resolve) => {
    console.log("a");
    resolve("promise result");
  });
}

doSomethingAsynchronous().then(function(pr) {
  console.log("c:" + pr);
});
console.log("b");

结果:

a
b
c:promise result

与身体中的异步代码相同的交易,除了不确定的延迟之前,在实现诺言之前,可以称为“然后”(点) C)。因此abdosomethingsasynchronous()返回时,才会立即打印实现(称为“解决”)。

一旦添加的调用,在表面上看起来很奇怪,即使在所有内容都同步时,b即使在c之前都打印出来。

当然,a会打印,然后c最后b

abc的原因是,无论身体中的代码是否为async,同步然后,方法总是通过Promise异步调用。

在我看来,我想象然后,方法被settimeout(()=> {then(pr)},0)promise promise promise promise中调用。一次resolve被调用。 IE当前的执行路径必须在传递到然后执行的函数之前完成。

Promise规范中不明显。

我的猜测是,它可以确保何时调用然后调用(始终在当前执行线程完成之后),这大概是允许多个Promises 在踢脚之前被堆叠/链接在一起将所有连续连续调用。

You can see below the body is executed immediately just by putting synchronous code in the body rather than asynchronous:

function doSomethingAsynchronous() {
  return new Promise((resolve) => {
    console.log("a");
    resolve("promise result");
  });
}
doSomethingAsynchronous();
console.log("b");

The result shows the promise body is executed immediately (before 'b' is printed).

The result of the Promise is retained, to be released to a 'then' call for example:

function doSomethingAsynchronous() {
  return new Promise((resolve) => {
    console.log("a");
    resolve("promise result");
  });
}

doSomethingAsynchronous().then(function(pr) {
  console.log("c:" + pr);
});
console.log("b");

Result:

a
b
c:promise result

The same deals with asynchronous code in the body except for the indeterminate delay before the promise is fulfilled and 'then' can be called (point c). So a and b would be printed as soon as doSomethingAsynchronous() returns but c appears only when the promise is fulfilled ('resolve' is called).

What looks odd on the surface once the call to then is added, is that b is printed before c even when everything is synchronous.

Surely a would print, then c and finally b?

The reason why a, b, and c are printed in that order is that no matter whether the code in the body is async or sync, the then method is always called asynchronously by the Promise.

In my mind, I imagine the then method being invoked by something like setTimeout(()=>{then(pr)},0) in the Promise once resolve is called. I.e. the current execution path must be complete before the function passed to then will be executed.

Not obvious from the Promise specification why it does this.

My guess is it ensures consistent behavior regarding when then is called (always after the current execution thread finishes) which is presumably to allow multiple Promises to be stacked/chained together before kicking off all the then calls in succession.

晨光如昨 2025-01-30 19:51:54

是的,当您构造Promise时,第一个参数将立即执行。

通常,您不会以您所做的方式真正使用Promise,就像当前的实现一样,它仍然是同步的。

您宁愿使用超时实现它,或将Resolve函数调用为AJAX回调的一部分,

function doSomethingAsynchronous() {
  return new Promise((resolve) => {
    setTimeout(function() {
      const result = doSomeWork();
      resolve(result);
    }, 0);
  });
}

settimeout方法将在下一个可能的时刻拨打该函数,事件队列免费

Yes, when you construct a Promise the first parameter gets executed immediately.

In general, you wouldn't really use a promise in the way you did, as with your current implementation, it would still be synchronous.

You would rather implement it with a timeout, or call the resolve function as part of an ajax callback

function doSomethingAsynchronous() {
  return new Promise((resolve) => {
    setTimeout(function() {
      const result = doSomeWork();
      resolve(result);
    }, 0);
  });
}

The setTimeout method would then call the function at the next possible moment the event queue is free

無處可尋 2025-01-30 19:51:54

来自 ecmascript规范

执行人函数立即由Promise执行
实施,通过解决和拒绝函数(执行者是
在承诺构造函数返回创建的对象之前调用)

考虑以下代码:

let asyncTaskCompleted = true

const executorFunction = (resolve, reject) => {
  console.log("This line will be printed as soon as we declare the promise");
  if (asyncTaskCompleted) {
    resolve("Pass resolved Value here");
  } else {
    reject("Pass reject reason here");
  }

}

const myPromise = new Promise(executorFunction)

当我们执行上述代码时,executorFunction将在声明Promise时自动调用,而无需明确调用它。

From the EcmaScript specification

The executor function is executed immediately by the Promise
implementation, passing resolve and reject functions (the executor is
called before the Promise constructor even returns the created object)

Consider the following code:

let asyncTaskCompleted = true

const executorFunction = (resolve, reject) => {
  console.log("This line will be printed as soon as we declare the promise");
  if (asyncTaskCompleted) {
    resolve("Pass resolved Value here");
  } else {
    reject("Pass reject reason here");
  }

}

const myPromise = new Promise(executorFunction)

When we execute the above code, executorFunction will be called automatically as soon as we declare the Promise, without us having to explicitly invoke it.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文