无论是ES6承诺还是蓝鸟承诺,Q承诺等等。
我如何测试,看看一个给定的对象是一个承诺?
无论是ES6承诺还是蓝鸟承诺,Q承诺等等。
我如何测试,看看一个给定的对象是一个承诺?
当前回答
这是https://github.com/ssnau/xkit/blob/master/util/is-promise.js的代码
!!obj && (typeof obj === 'object' || typeof obj === 'function') && typeof obj.then === 'function';
如果一个对象具有then方法,它应该被视为Promise。
其他回答
我用这个函数作为通用解:
function isPromise(value) {
return value && value.then && typeof value.then === 'function';
}
角:
import { isPromise } from '@angular/compiler/src/util';
if (isPromise(variable)) {
// do something
}
J
任何为了避免比较而将可能同步的值推入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
我还没有对任何非本地库进行检查,但现在有什么意义呢?
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));
});
if (typeof thing?.then === 'function') {
// probably a promise
} else {
// definitely not a promise
}