How do I tell if an object is a Promise?

2019-01-04 06:33发布

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

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

14条回答
萌系小妹纸
2楼-- · 2019-01-04 07:16

ES6:

const promise = new Promise(resolve => resolve('olá'));

console.log(promise.toString().includes('Promise')); //true
查看更多
劫难
3楼-- · 2019-01-04 07:19

Here's my original answer, which has since been ratified in the spec as the way to test for a promise:

Promise.resolve(obj) == obj

This works because the algorithm explicitly demands that Promise.resolve must return the exact object passed in if and only if it is a promise by the definition of the spec.

I have another answer here, which used to say this, but I changed it to something else when it didn't work with Safari at that time. That was a year ago, and this now works reliably even in Safari.

I would have edited my original answer, except that felt wrong, given that more people by now have voted for the altered solution in that answer than the original. I believe this is the better answer, and I hope you agree.

查看更多
登录 后发表回答