从 Promise 中检索数据:then() 和 catch()

2025-06-10

从 Promise 中检索数据:then() 和 catch()

亲爱的读者和开发者们,大家好!

在上一篇文章中,我展示了如何创建Promise,这是一个非常重要的概念。
[ https://dev.to/swarnaliroy94/javascript-concept-of-promise-3ijb ]

生成 Promise 后,pending状态立即开始,并保持到被 resolverejected为止。
话虽如此,在使用 React.JS 或 React Native 时,我们可以将初始状态设置为pending状态,并在部分中设置resolvethen,并在 部分中设置rejectioncatch

那么问题来了,这个then&catch部分是什么呢?

JavaScript中,我们经常难以处理异步操作。Promise 的概念应运而生,我们可以用它来处理这些操作。要理解如何从Promise中获取数据,then& 的catch概念至关重要。

题外话,我之前费了好大劲才理解Promise 的工作原理。到现在已经过去 8 个月了,根据我积累的经验,我会尽量把这篇文章写得通俗易懂。

让我们开始了解如何从 Promise 中检索数据

首先,我们来创建一个承诺作为例子。

const addition = (a, b) =>
  new Promise((resolve, reject) => {
    if (typeof a == "number" && typeof b == "number") {
      resolve(a + b);
    } else {
        reject ("Not a Number")
    }
  });
Enter fullscreen mode Exit fullscreen mode

示例展示了一个名为addition的函数,它Promise接受两个参数ab。 if 代码块包含一个条件语句,使用typeof运算符检查 a 和 b 是否均为数字。
[ https://dev.to/swarnaliroy94/javascript-data-types-and-debugging-type-errors-with-typeof-3mao ]。

解决

当我们执行上面例子中创建的 Promise 时,如果它被解析了,相应的代码块就会被执行,我们可以从回调函数then中获取结果。在这个例子中,当且仅当 a 和 b 都是数字时,这个 Promise 才会被解析并返回 a 和 b 的和。示例如下。

addition(10, 5)
  .then((response) => {
    console.log(response);
  })
  .catch((err) => {
    console.log(err);
  });
Enter fullscreen mode Exit fullscreen mode

示例的输出将显示总和 15,因为 10 和 5 都是数字

拒绝

如果 a 或 b 中的任何一个值不是数字,则 Promise 将被拒绝并且将被捕获在块中。catch

addition(10, "5") 
  .then((response) => {
    console.log(response);
  })
  .catch((err) => {
    console.log(err);
  });
Enter fullscreen mode Exit fullscreen mode

示例的输出显示消息“Not a Number” ,因为 10 是一个数字但“5”是一个字符串,这不满足 Promise 的条件。

基本上,then捕获成功状态并catch捕获错误/失败状态。

还有其他方法可以实现相同的概念。我们可以使用 Async/Await 使其更紧凑。我将在下一篇文章中讨论这个问题。我希望我能够使其简单易懂。但是,如果您有任何疑问,欢迎随时在讨论区提问。

鏂囩珷鏉ユ簮锛�https://dev.to/swarnaliroy94/retrieve-data-from-promise-then-catch-3onk
PREV
在 JavaScript 中反转字符串
NEXT
Promise 的方法:.all()、.any()、.finally()、.race()