1. 判断一个值是否为 Promise-like 对象(thenable)
- Promise-like 对象指的是具有 'then' 方法的对象,也就是所谓的 "thenable" 对象。
export function isPromiseLike(value) {
return value !== null
&& (typeof value === 'object' || typeof value === 'function')
&& typeof value.then === 'function';
}
const thenable = {
then: function(resolve) {
resolve(42);
}
};
console.log(isPromiseLike(thenable));
console.log(isPromiseLike(null));
console.log(isPromiseLike(undefined));
console.log(isPromiseLike(42));
console.log(isPromiseLike({}));
console.log(isPromiseLike({ then: 42 }));
2. 判断一个值是否为原生 Promise 实例
- 使用
instanceof 判断
- 只匹配原生 Promise 实例
export function isNativePromise(value) {
return value instanceof Promise;
}
const promise = Promise.resolve(42);
console.log(isPromiseLike(promise));
console.log(isNativePromise(promise));
console.log(isNativePromise(thenable));
3. 判断一个值是否为异步函数
export function isAsync(value) {
return typeof value === 'function' && value.constructor.name === 'AsyncFunction';
}
const asyncFn = async () => {};
console.log(isAsync(asyncFn));
console.log(isAsync(() => {}));
这些工具函数在以下场景特别有用:
- 处理可能返回 Promise 或普通值的函数
- 实现通用的异步处理逻辑
- 在中间件或拦截器中判断返回值类型
- 处理第三方库返回的 Promise-like 对象