无论是ES6承诺还是蓝鸟承诺,Q承诺等等。
我如何测试,看看一个给定的对象是一个承诺?
无论是ES6承诺还是蓝鸟承诺,Q承诺等等。
我如何测试,看看一个给定的对象是一个承诺?
当前回答
如果你正在使用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
其他回答
这是graphql-js包检测承诺的方式:
function isPromise(value) {
return Boolean(value && typeof value.then === 'function');
}
Value是函数的返回值。我在我的项目中使用这段代码,到目前为止还没有问题。
这并不是完整问题的答案,但我认为值得一提的是,在Node.js 10中添加了一个名为isPromise的新util函数,它可以检查对象是否为本机Promise:
const utilTypes = require('util').types
const b_Promise = require('bluebird')
utilTypes.isPromise(Promise.resolve(5)) // true
utilTypes.isPromise(b_Promise.resolve(5)) // false
我用这个函数作为通用解:
function isPromise(value) {
return value && value.then && typeof value.then === 'function';
}
if (typeof thing?.then === 'function') {
// probably a promise
} else {
// definitely not a promise
}
如果你正在使用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