无论是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));
});

其他回答

免责声明:更新OP不是一个很好的答案,是每个库,不会跨领域工作。改为检查。then。

这个基于规范的答案是一种测试承诺的方法,仅供参考。

Promise.resolve(obj) == obj &&
BLUEBIRD.resolve(obj) == obj

当它起作用时,是因为算法明确地要求Promise。当且仅当它是此构造函数创建的promise时,Resolve必须返回传入的确切对象。

这是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,它将等待并返回已解析的值。如果函数返回一个值,它将被视为已解析。

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

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

角:

import { isPromise } from '@angular/compiler/src/util';

if (isPromise(variable)) {
  // do something
}

J