我如何判断一个对象是否是一个 Promise? [英] How do I tell if an object is a Promise?

查看:43
本文介绍了我如何判断一个对象是否是一个 Promise?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

无论是 ES6 Promise 还是 bluebird Promise、Q Promise 等

Whether it's an ES6 Promise or a bluebird Promise, Q Promise, etc.

我如何测试一个给定的对象是否是一个 Promise?

How do I test to see if a given object is a Promise?

推荐答案

promise 库如何决定

如果它有一个 .then 函数 - 那是 唯一 使用的标准承诺库.

How a promise library decides

If it has a .then function - that's the only standard promise libraries use.

Promises/A+ 规范有一个名为 thenable 的概念,它基本上是具有 then 方法的对象".Promise 将并且应该使用 then 方法吸收任何东西.你提到的所有承诺实现都是这样做的.

The Promises/A+ specification has a notion called thenable which is basically "an object with a then method". Promises will and should assimilate anything with a then method. All of the promise implementation you've mentioned do this.

如果我们查看规范:

2.3.3.3 如果 then 是一个函数,用 x 作为 this 调用它,第一个参数是 resolvePromise,第二个参数是 rejectPromise

2.3.3.3 if then is a function, call it with x as this, first argument resolvePromise, and second argument rejectPromise

它还解释了此设计决策的基本原理:

It also explains the rationale for this design decision:

这种对 thenables 的处理允许 promise 实现互操作,只要它们公开一个符合 Promises/A+ 的 then 方法.它还允许 Promises/A+ 实现使用合理的 then 方法吸收"不一致的实现.

This treatment of thenables allows promise implementations to interoperate, as long as they expose a Promises/A+-compliant then method. It also allows Promises/A+ implementations to "assimilate" nonconformant implementations with reasonable then methods.

你应该如何决定

你不应该 - 而是调用 Promise.resolve(x)(Q 中的 Q(x)),它会总是转换任何值或外部 then 能够转换为可信承诺.比自己进行这些检查更安全、更容易.

How you should decide

You shouldn't - instead call Promise.resolve(x) (Q(x) in Q) that will always convert any value or external thenable into a trusted promise. It is safer and easier than performing these checks yourself.

您始终可以通过测试套件来运行它:D

You can always run it through the test suite :D

这篇关于我如何判断一个对象是否是一个 Promise?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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