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

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

问题描述

我正在使用 bluebird,我看到了两种将同步函数解析为 Promise 的方法,但我不明白这两种方法之间的区别.看起来堆栈跟踪有点不同,所以它们不仅仅是一个别名,对吧?

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?

那么首选的方式是什么?

So what is the preferred way?

方式 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 返回函数通常应该保证它们不应该同步抛出,因为它们可能会异步抛出.为了防止意外结果和竞争条件 - 通常将抛出转换为返回的拒绝.

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 会为你将 throws 转换为 rejects 并返回到 resolves.这是最安全的方法,它通过返回值吸收thenables,因此即使someObject实际上是一个promise本身,它也能工作.

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 用于将对象和外部承诺(thenables)转换为承诺.这就是它的用例.

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

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

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