无论是ES6承诺还是蓝鸟承诺,Q承诺等等。
我如何测试,看看一个给定的对象是一个承诺?
无论是ES6承诺还是蓝鸟承诺,Q承诺等等。
我如何测试,看看一个给定的对象是一个承诺?
当前回答
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://github.com/ssnau/xkit/blob/master/util/is-promise.js的代码
!!obj && (typeof obj === 'object' || typeof obj === 'function') && typeof obj.then === 'function';
如果一个对象具有then方法,它应该被视为Promise。
如果你在一个异步方法中,你可以这样做,避免任何歧义。
async myMethod(promiseOrNot){
const theValue = await promiseOrNot()
}
如果函数返回promise,它将等待并返回已解析的值。如果函数返回一个值,它将被视为已解析。
如果函数今天没有返回一个承诺,但明天返回一个承诺,或者被声明为异步,那么你将是不受未来影响的。
角:
import { isPromise } from '@angular/compiler/src/util';
if (isPromise(variable)) {
// do something
}
J
const isPromise = (value) => {
return !!(
value &&
value.then &&
typeof value.then === 'function' &&
value?.constructor?.name === 'Promise'
)
}
对我来说,这张支票更好,试试吧
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));
});