Promise.resolve vs new Promise(resolve)

Pipo提出了一个问题:Promise.resolve vs new Promise(resolve),或许与您遇到的问题类似。

回答者Abdullah KhanBenjamin Gruenbaum给出了该问题的处理方式:

Contrary to both answers in the comments - there is a difference.

While Promise.resolve(x); is basically the same as new Promise(function(r){ r(x); }); there is a subtlety.

Promise returning functions should generally have the guarantee that they should not throw synchronously since they might throw asynchronously. In order to prevent unexpected results and race conditions - throws are usually converted to returned rejections.

With this in mind - when the spec was created the promise constructor is throw safe.

What if someObject is undefined?

  • Way A returns a rejected promise.
  • Way B throws synchronously.

Bluebird saw this, and Petka added Promise.method to address this issue so you can keep using return values. So the correct and easiest way to write this in Bluebird is actually neither - it is:

var someFunction = Promise.method(function someFunction(someObject){
    someObject.resolved = true;
    return someObject;

Promise.method will convert throws to rejects and returns to resolves for you. It is the most throw safe way to do this and it assimilatesthenables through return values so it'd work even if someObject is in fact a promise itself.

In general, Promise.resolve is used for casting objects and foreign promises (thenables) to promises. That's its use case.



欢迎 JavaScript 爱好者