Promise.resolve与新Promise(resolve) [英] Promise.resolve vs new Promise(resolve)

查看:431
本文介绍了Promise.resolve与新Promise(resolve)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用bluebird,我看到了两种将同步功能解析为Promise的方法,但是我没有得到两种方法之间的区别.看起来stacktrace有点不同,所以它们不只是alias,对吧?

I'm using bluebird and I see two ways to resolve synchronous functions into a Promise, but I don't get the differences between both ways. It looks like the stacktrace is a little bit different, so they aren't just an alias, right?

那首选的方法是什么?

A路

function someFunction(someObject) {
  return new Promise(function(resolve) {
    someObject.resolved = true;
    resolve(someObject);
  });
}

B路

function someFunction(someObject) {
  someObject.resolved = true;
  return Promise.resolve(someObject);
}

推荐答案

与注释中的两个答案相反-有所不同.

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

Promise.resolve(x);

基本上与

new Promise(function(r){ r(x); });

有一个微妙的地方.

有保证的返回函数通常应保证它们不应异步抛出,因为它们可能异步抛出.为了防止出现意外结果和比赛状况,通常将罚球转换为退回的罚单.

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.

请牢记这一点-创建规范时,promise构造函数是安全的.

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

  • 方式A返回被拒绝的承诺.
  • 路B同步投掷.

Bluebird看到了这一点,Petka添加了Promise.method来解决此问题,因此您可以继续使用返回值.因此,在Bluebird中编写此代码的正确,最简单的方法实际上既不是-而是:

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将为您将引发转换为拒绝,然后返回解决.这是最安全的方法,它通过返回值来同化then ables,因此即使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.

通常,Promise.resolve用于将对象和外国承诺(thenable)投射到承诺.这就是它的用例.

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

这篇关于Promise.resolve与新Promise(resolve)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆