JavaScript 中检查函数是否返回 Promise
要检查函数是否返回Promise
,请检查函数是否异步或调用它并检查函数是否返回具有函数类型 then 属性的对象。 如果满足任一条件,该函数将返回一个 Promise
。
// ✅ Promise check
function isPromise(p) {
if (typeof p === 'object' && typeof p.then === 'function') {
return true;
}
return false;
}
// ✅ Check if return value is promise
function returnsPromise(f) {
if (
f.constructor.name === 'AsyncFunction' ||
(typeof f === 'function' && isPromise(f()))
) {
console.log('✅ Function returns promise');
return true;
}
console.log('⛔️ Function does NOT return promise');
return false;
}
// 👇️ Examples
async function exampleAsync() {}
function example() {}
function examplePromise() {
return new Promise(resolve => {
resolve(42);
});
}
console.log(returnsPromise(exampleAsync)); // 👉️ true
console.log(returnsPromise(example)); // 👉️ false
console.log(returnsPromise(examplePromise)); // 👉️ true
代码片段中的第一个函数检查传入的值是否为 Promise。
第二个函数将另一个函数作为参数并检查它的返回值是否是一个 promise。
if
语句中的第一个条件检查函数是否是异步的。
每个异步函数都会返回一个
promise
,因此如果该函数是异步的,我们会立即断定它会返回一个promise
。
我们的第二个条件检查传入的值是否是一个函数并调用它,将结果传递给 isPromise() 函数。
检查非异步函数是否返回承诺的唯一方法是调用它。 请注意,如果它改变状态,调用函数可能不安全,例如 写入数据库。
有两种方法可以检查一个函数是否返回一个 promise
:
-
检查函数是否异步——然后它会
100%
地返回一个promise
- 检查函数的返回值是否是具有函数类型 then 属性的对象。
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
如何在 JavaScript 中合并两个数组而不出现重复的情况
发布时间:2024/03/23 浏览次数:86 分类:JavaScript
-
本教程介绍了如何在 JavaScript 中合并两个数组,以及如何删除任何重复的数组。