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

查看:1985
本文介绍了如何判断对象是否为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 +规范有一个名为然后的概念,它基本上是一个<$ c的对象$ c>然后方法。承诺将并且应该使用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.

你可以随时通过< a href =https://github.com/promises-aplus/promises-tests =noreferrer>测试套件:D

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

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