解析函数是否异步传递给 Promise 执行器?

Nat*_*aia 5 javascript node.js promise

我有以下代码:

function myPromiseFunc() {
  return new Promise((resolve) => {
    resolve(Promise.resolve(123));
  });
}
Run Code Online (Sandbox Code Playgroud)

正如我们所知,Promise.resolve方法立即用普通值解析 Promise。所以Promise.resolve(123) -> Promise<fulfilled> 但是:

console.log(myPromiseFunc());
Run Code Online (Sandbox Code Playgroud)

将返回带有 status 的 Promise pending。为什么?解析函数是否异步传递给执行器?导致这个:

setTimeout(console.log, 0, res);
Run Code Online (Sandbox Code Playgroud)

将返回Promise<fulfilled>

我知道 Promise 使用微任务,但它应该只用于处理程序。

承诺/A+说:

[[解决]](承诺, x) ->If/when x is a promise and fulfilled, fulfill promise with the same value.

顺便一提。这个片段将返回Promise<fulfilled>

function myPromiseFunc() {
  return new Promise((resolve) => {
    resolve(123);
  });
}
Run Code Online (Sandbox Code Playgroud)

所以看起来resolve只有当 Promise 作为值传递时才是异步的。

请大家帮忙理解一下。谢谢你!

Kel*_*ofs 4

根据传递给执行器的函数的规范resolvenew Promise((resolve, reject) => ...)

当使用参数调用 Promise 解析函数时resolution,将执行以下步骤:

  1. F为活动函数对象。
  2. Assert:F有一个[[Promise]]内部槽,其值为一个对象。
  3. promise这样吧F.[[Promise]]
  4. alreadyResolved这样吧F.[[AlreadyResolved]]
  5. 如果alreadyResolved.[[Value]]true,则返回undefined
  6. 设置。alreadyResolved.[[Value]]true
  7. 如果SameValue(resolution, promise)true,那么
    1. selfResolutionError成为一个新创建的TypeError对象。
    2. 返回RejectPromise(promise, selfResolutionError)
  8. 如果Type(resolution)不是对象,那么
    1. 返回FulfillPromise(promise, resolution)
  9. then这样吧Get(resolution, "then")
  10. 如果then是突然完成,那么
    1. 返回RejectPromise(promise, then.[[Value]])
  11. thenAction这样吧then.[[Value]]
  12. 如果IsCallable(thenAction)false,那么
    1. 返回FulfillPromise(promise, resolution)
  13. thenJobCallback这样吧HostMakeJobCallback(thenAction)
  14. job这样吧NewPromiseResolveThenableJob(promise, resolution, thenJobCallback)
  15. 履行HostEnqueuePromiseJob(job.[[Job]], job.[[Realm]])
  16. 返回undefined

有很多技术术语,但对于您的问题来说,最重要的是 resolution 您传递给它的值。如果它(大致)是一个非 Promise,那么您最终会进入8.1(对于非对象)或12.1(对于丢失或不可调用的then字段),这都将立即履行承诺。如果您使用函数(例如 Promise)传递一个值,它将执行从基本上排队的位置then开始的所有步骤,并遵循整个“我的实现取决于另一个 Promise 的实现”。13.then