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

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


当前回答

我用这个函数作为通用解:

function isPromise(value) {
  return value && value.then && typeof value.then === 'function';
}

其他回答

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。

角:

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

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

J

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

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

})

这是graphql-js包检测承诺的方式:

function isPromise(value) {
  return Boolean(value && typeof value.then === 'function');
}

Value是函数的返回值。我在我的项目中使用这段代码,到目前为止还没有问题。