📌  相关文章
📜  为什么我们在 JavaScript 中使用 then() 方法?(1)

📅  最后修改于: 2023-12-03 14:48:56.621000             🧑  作者: Mango

为什么我们在 JavaScript 中使用 then() 方法?

在 JavaScript 中,Promise 是一种用于异步编程的对象,可以在异步操作完成之前立即返回。Promise 的 then() 方法用于指定在 Promise 完成时要执行的操作,该方法接收两个可选参数:onFulfilled 和 onRejected 回调函数。

简介

then() 方法是 Promise 的一部分,它可以用于设置 Promise 成功执行和失败执行的回调函数。它也可以返回另一个 Promise 对象以允许链式调用。

通常,我们使用 then() 方法来执行一些操作,而这些操作既可以成功执行,也可以失败执行。因此,在 then() 方法中,我们需要传递两个函数作为其参数:一个用于处理 Promise 成功的回调函数,另一个用于处理 Promise 失败的回调函数。

语法
promise.then(onFulfilled, onRejected)
  • onFulfilled(可选):当 Promise 实例状态变为 fulfilled 时的回调函数。
  • onRejected(可选):当 Promise 实例状态变为 rejected 时的回调函数。
例子
const promise = new Promise((resolve, reject) => {
  // 模拟异步操作
  setTimeout(() => {
    const isSuccessful = true;
    if (isSuccessful) {
      resolve('Success!');
    } else {
      reject('Error!');
    }
  }, 1000);
});

promise
  .then((response) => {
    console.log(response);
  })
  .catch((error) => {
    console.error(error);
  });

当 Promise 对象的状态变为 fulfilled 时,then() 方法中的第一个回调函数会被执行。相反,当 Promise 对象的状态变为 rejected 时,then() 方法中的第二个回调函数会被执行。在上面的示例中,如果异步操作成功,则成功回调函数会打印“Success!”;如果异步操作失败,则失败回调函数会打印“Error!”。

链式调用

由于 then() 方法返回一个 Promise 对象,因此我们可以进行链式调用。例如:

promise
  .then((response) => {
    console.log(response);
    return 'Step 1 Done!';
  })
  .then((response) => {
    console.log(response);
    return 'Step 2 Done!';
  })
  .then((response) => {
    console.log(response);
  })
  .catch((error) => {
    console.error(error);
  });

在上面的示例中,我们在每个成功回调中返回一个字符串,然后继续链式调用。如果在链式调用期间出现任何错误,则将跳过后续 then() 方法并调用失败回调函数。

总结

在 JavaScript 中,then() 方法被用于设置 Promise 成功执行和失败执行的回调函数,并允许链式调用。它接收两个可选参数:onFulfilled 和 onRejected 回调函数。在成功回调中,我们通常需要返回一个值来继续链式调用。当在链式调用期间出现错误时,失败回调函数会被调用。