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

其他回答

const isPromise = (value) => {
  return !!(
    value &&
    value.then &&
    typeof value.then === 'function' &&
    value?.constructor?.name === 'Promise'
  )
}

对我来说,这张支票更好,试试吧

任何为了避免比较而将可能同步的值推入Promise.resolve(value)的操作都会使代码变成原本可以避免的异步。有时候在那个阶段你不想要它。你想知道在微任务队列中的一些早期解决方案咬你之前的结果。?

一个人可以做喜欢的事;

var isPromise = x => Object(x).constructor === Promise;

我检查了一些我能想到的边缘情况,它似乎工作。

isPromise(undefined);                                           // <- false
isPromise(null);                                                // <- false
isPromise(0);                                                   // <- false
isPromise("");                                                  // <- false
isPromise({});                                                  // <- false
isPromise(setTimeout);                                          // <- false
isPromise(Promise);                                             // <- false
isPromise(new Promise((v,x) => setTimeout(v,1000,"whatever"))); // <- true
isPromise(fetch('http://example.com/movies.json'));             // <- true

我还没有对任何非本地库进行检查,但现在有什么意义呢?

如果你正在使用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是函数的返回值。我在我的项目中使用这段代码,到目前为止还没有问题。

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

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

})