📜  js .then mean - Javascript (1)

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

JavaScript 中的 .then 方法

在 JavaScript 中,.then 方法是 Promise 对象的一种处理方式,它用于处理 Promise 对象返回成功时所需要执行的操作。本文将对 .then 方法进行介绍。

Promise 对象

Promise 是 ES6 中新增的一个构造函数,它是一种异步编程的解决方案。Promise 对象的基本使用方法如下所示:

// 创建 Promise 对象
const promise = new Promise((resolve, reject) => {
  // 异步操作
  setTimeout(() => {
    // 成功时,调用 resolve 并传入参数
    resolve('data');
    // 失败时,调用 reject 并传入参数
    // reject('error');
  }, 1000);
});

// 调用 Promise 对象的 .then 方法
promise.then((data) => {
  console.log(data);
}).catch((error) => {
  console.log(error);
});

以上代码会在 1 秒后打印出 'data'。

.then 方法的基本使用

在 Promise 对象返回成功时,可以通过 .then 方法来处理需要执行的操作。.then 方法接收一个回调函数作为参数,该回调函数会在 Promise 对象返回成功时被调用。

promise.then((data) => {
  console.log(data);
});

以上代码会在 Promise 对象返回成功时执行回调函数,并将 Promise 对象返回的数据作为参数传入回调函数中。

在 .then 方法中也可以返回 Promise 对象,这样就可以实现链式调用多个 .then 方法来依次处理 Promise 对象返回的数据。

promise
  .then((data) => {
    console.log(data);
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve('data2');
      }, 1000);
    });
  })
  .then((data) => {
    console.log(data);
  });

以上代码会在 1 秒后打印出 'data2'。

.then 方法的链式调用

链式调用多个 .then 方法可以依次处理 Promise 对象返回的数据。

promise
  .then((data) => {
    console.log(data);
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve('data2');
      }, 1000);
    });
  })
  .then((data) => {
    console.log(data);
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve('data3');
      }, 1000);
    });
  })
  .then((data) => {
    console.log(data);
  });

以上代码会在 2 秒后打印出 'data3'。

.then 方法的参数

在 .then 方法中,还可以传入两个参数,分别为成功回调函数和失败回调函数。

promise
  .then((data) => {
    console.log(data);
  }, (error) => {
    console.log(error);
  });

以上代码会在 Promise 对象返回成功时执行第一个回调函数,返回失败时执行第二个回调函数。

.then 方法的异常处理

在 .then 方法中,如果执行回调函数时抛出异常,会直接进入 Promise 对象的 catch 方法中。

promise
  .then((data) => {
    throw new Error('error');
  })
  .then((data) => {
    console.log(data);
  })
  .catch((error) => {
    console.log(error);
  });

以上代码会在 Promise 对象返回失败时进入 catch 方法中,并打印出 'error'。在 .then 方法中也可以捕获异常并返回 Promise 对象来处理异常情况。

promise
  .then((data) => {
    throw new Error('error');
  }, (error) => {
    console.log(error);
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve('data2');
      }, 1000);
    });
  })
  .then((data) => {
    console.log(data);
  })
  .catch((error) => {
    console.log(error);
  });

以上代码会在 Promise 对象返回失败时执行第二个回调函数,并返回一个新的 Promise 对象来处理异常情况。1 秒后,该 Promise 对象返回成功,并打印出 'data2'。如果没有返回新的 Promise 对象,该异常会直接进入下一个 .then 方法中的 catch 方法。