如何在 JavaScript 中检查函数是否异步
要检查函数是否异步,请访问函数的 constructor.name
属性并检查该值是否等于 AsyncFunction
,例如 myFunction.constructor.name === 'AsyncFunction'
。 如果相等性检查返回 true,则该函数是异步的。
const sum = async (a, b) => {
return a + b;
};
if (sum.constructor.name === 'AsyncFunction') {
// 👇️ this runs
console.log('✅ function is async');
} else {
console.log('⛔️ function is NOT async');
}
访问函数时,constructor
属性返回:
- 非异步函数的函数构造函数
-
异步函数的
AsyncFunction
构造函数
JavaScript 中的每个异步函数都是一个 AsyncFunction
对象。
最后一步是访问构造函数的名称属性,并检查是否使用 AsyncFunction 构造函数来创建函数。
如果条件通过,那么我们就有了一个异步函数。
这种方法适用于箭头和命名函数。
如果我们访问非异步函数的 name 属性,则会返回字符串“Function”。
function example() {}
console.log(example.constructor.name); // 👉️ "Function"
不同的构造函数用于创建异步和非异步函数,因此我们可以很容易地判断一个函数是否是异步的。
请记住
,非异步函数可能会返回一个 promise。
// 👇️ non-async returns Promise
function example() {
return new Promise(resolve => {
resolve(100);
});
}
console.log(example()); // 👉️ Promise {}
console.log(example.constructor.name); // 👉️ "Function"
该示例显示了一个返回承诺的非异步函数。
了解非异步函数是否返回承诺的唯一方法是调用该函数。
我们可以通过以下方式检查函数的返回值是否为 Promise。
function example() {
return new Promise(resolve => {
resolve(100);
});
}
function isPromise(p) {
if (typeof p === 'object' && typeof p.then === 'function') {
return true;
}
return false;
}
console.log(isPromise(example())); // 👉️ true
console.log(isPromise(() => {})); // 👉️ false
我们检查传入的值是否是一个对象,并且它包含一个名为 then
的属性,该属性属于函数类型。
这种方法会失败,因为有人传递了一个对象,该对象的
then
类型函数的属性实际上不是一个承诺。
大多数时候你不能仅仅调用函数来检查它们的返回值是什么,因为它们可能正在改变状态,例如 在数据库中。
但是,如果我们可以在不改变任何状态的情况下调用该函数,则可以组合这两个条件。
if (
example.constructor.name === 'AsyncFunction' ||
(typeof example === 'function' && isPromise(example()))
) {
console.log('✅ Function returns promise');
} else {
console.log('⛔️ Function does NOT return promise');
}
我们的 if
语句检查函数是异步的还是返回一个 promise。 如果任一检查通过,则 if
块运行。
相关文章
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 中合并两个数组,以及如何删除任何重复的数组。