迹忆客 专注技术分享

当前位置:主页 > 学无止境 > WEB前端 > JavaScript >

JavaScript 中检查函数是否返回 Promise

作者:迹忆客 最近更新:2022/12/02 浏览次数:

要检查函数是否返回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

JavaScript 中检查函数是否返回 Promise

代码片段中的第一个函数检查传入的值是否为 Promise。

第二个函数将另一个函数作为参数并检查它的返回值是否是一个 promise。

if 语句中的第一个条件检查函数是否是异步的。

每个异步函数都会返回一个 promise,因此如果该函数是异步的,我们会立即断定它会返回一个 promise

我们的第二个条件检查传入的值是否是一个函数并调用它,将结果传递给 isPromise() 函数。

检查非异步函数是否返回承诺的唯一方法是调用它。 请注意,如果它改变状态,调用函数可能不安全,例如 写入数据库。

有两种方法可以检查一个函数是否返回一个 promise

  1. 检查函数是否异步——然后它会 100% 地返回一个 promise
  2. 检查函数的返回值是否是具有函数类型 then 属性的对象。

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

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 POST

发布时间:2024/03/23 浏览次数:96 分类:JavaScript

本教程讲解如何在不使用 JavaScript 表单的情况下发送 POST 数据。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便