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 06:54

Update: This is no longer the best answer. Please vote up my other answer instead.

obj instanceof Promise

should do it. Note that this may only work reliably with native es6 promises.

If you're using a shim, a promise library or anything else pretending to be promise-like, then it may be more appropriate to test for a "thenable" (anything with a .then method), as shown in other answers here.

查看更多
Melony?
3楼-- · 2019-01-04 06:54
it('should return a promise', function() {
    var result = testedFunctionThatReturnsPromise();
    expect(result).toBeDefined();
    // 3 slightly different ways of verifying a promise
    expect(typeof result.then).toBe('function');
    expect(result instanceof Promise).toBe(true);
    expect(result).toBe(Promise.resolve(result));
});
查看更多
Evening l夕情丶
4楼-- · 2019-01-04 06:54

after searching for a reliable way to detect Async functions or even Promises, i ended up using the following test :

() => fn.constructor.name === 'Promise' || fn.constructor.name === 'AsyncFunction'
查看更多
贼婆χ
5楼-- · 2019-01-04 06:57

Checking if something is promise unnecessarily complicates the code, just use Promise.resolve

Promise.resolve(valueOrPromiseItDoesntMatter).then(function(value) {

})
查看更多
淡お忘
6楼-- · 2019-01-04 06:58

If you are in an async method you can do this and avoid any ambiguity.

async myMethod(promiseOrNot){
  const theValue = await promiseOrNot
}

If the function returns promise, it will await and return with the resolved value. If the function returns a value, it will be treated as resolved.

查看更多
Lonely孤独者°
7楼-- · 2019-01-04 07:00

In case you are using Typescript, I'd like to add that you can use the "type predicate" feature. Just should wrap the logical verification in a function that returns x is Promise<any> and you won't need to do typecasts. Below on my example, c is either a promise or one of my types which I want to convert into a promise by calling the c.fetch() method.

export function toPromise(c: Container<any> | Promise<any>): Promise<any> {
    if (c == null) return Promise.resolve();
    return isContainer(c) ? c.fetch() : c;
}

export function isContainer(val: Container<any> | Promise<any>): val is Container<any> {
    return val && (<Container<any>>val).fetch !== undefined;
}

export function isPromise(val: Container<any> | Promise<any>): val is Promise<any> {
    return val && (<Promise<any>>val).then !== undefined;
}

More info: https://www.typescriptlang.org/docs/handbook/advanced-types.html

查看更多
登录 后发表回答