如何判断对象是否为Promise?

如何判断对象是否为Promise?

问题描述:

无论是ES6 Promise还是蓝鸟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?

承诺库如何决定



如果它有 .then function - 这是标准承诺库使用的。

How a promise library decides

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

Promises / A +规范有一个名为然后的概念,它基本上是一个然后方法。承诺将并且应该使用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 if then 是一个函数,用x调用它,第一个参数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:


这种处理然后 ables允许承诺实现互操作,只要他们公开一个Promises / A +兼容的然后方法。它还允许Promises / A +实现用合理的方法同化不一致的实现。

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(x)在Q中)始终将任何值或外部然后转换为可信承诺。它比自己执行这些检查更安全,更容易。

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