无论是ES6承诺还是蓝鸟承诺,Q承诺等等。

我如何测试,看看一个给定的对象是一个承诺?


当前回答

检查是否有不必要的承诺会使代码变得复杂,只需使用promise .resolve

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

})

其他回答

检查是否有不必要的承诺会使代码变得复杂,只需使用promise .resolve

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

})
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));
});

如果你在一个异步方法中,你可以这样做,避免任何歧义。

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

如果函数返回promise,它将等待并返回已解析的值。如果函数返回一个值,它将被视为已解析。

如果函数今天没有返回一个承诺,但明天返回一个承诺,或者被声明为异步,那么你将是不受未来影响的。

if (typeof thing?.then === 'function') {
    // probably a promise
} else {
    // definitely not a promise
}

这是https://github.com/ssnau/xkit/blob/master/util/is-promise.js的代码

!!obj && (typeof obj === 'object' || typeof obj === 'function') && typeof obj.then === 'function';

如果一个对象具有then方法,它应该被视为Promise。