无论是ES6承诺还是蓝鸟承诺,Q承诺等等。
我如何测试,看看一个给定的对象是一个承诺?
无论是ES6承诺还是蓝鸟承诺,Q承诺等等。
我如何测试,看看一个给定的对象是一个承诺?
当前回答
在寻找一个可靠的方法来检测Async函数甚至承诺后,我最终使用了以下测试:
() => fn.constructor.name === 'Promise' || fn.constructor.name === 'AsyncFunction'
其他回答
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));
});
使用这个库
https://www.npmjs.com/package/is-promise
import isPromise from 'is-promise';
isPromise(Promise.resolve());//=>true
isPromise({then:function () {...}});//=>true
isPromise(null);//=>false
isPromise({});//=>false
isPromise({then: true})//=>false
如果你正在使用Typescript,我想补充一点,你可以使用“类型谓词”功能。只应该将逻辑验证包装在返回x is Promise<any>的函数中,您不需要进行类型转换。在下面的示例中,c要么是一个promise,要么是我想通过调用c.fetch()方法将其转换为promise的类型之一。
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;
}
更多信息:https://www.typescriptlang.org/docs/handbook/advanced-types.html
角:
import { isPromise } from '@angular/compiler/src/util';
if (isPromise(variable)) {
// do something
}
J
if (typeof thing?.then === 'function') {
// probably a promise
} else {
// definitely not a promise
}