RELATEED CONSULTING
相关咨询
选择下列产品马上在线沟通
服务时间:8:30-17:00
你可能遇到了下面的问题
关闭右侧工具栏

新闻中心

这里有您想知道的互联网营销解决方案
JavaScrpt中的函数then是什么意思

then() 是 JavaScript 中 Promise 对象的一个方法,用于处理异步操作的结果,当 Promise 对象的状态变为 resolved(成功)时,then() 方法会被调用,并将结果传递给指定的回调函数。then() 方法返回一个新的 Promise 对象,可以继续链式调用其他 then() 方法或 catch() 方法。

then() 方法的基本用法

1、接收两个参数:第一个参数是 Promise 状态变为 resolved 时执行的回调函数,第二个参数是 Promise 状态变为 rejected 时执行的回调函数。

2、回调函数接收一个参数,即 Promise 的结果值。

3、如果只关心 Promise 成功时的结果,可以省略第二个参数。

示例代码:

const promise = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve('成功');
  }, 1000);
});
promise.then(
  (result) => {
    console.log('成功:', result);
  },
  (error) => {
    console.log('失败:', error);
  }
);

then() 方法的链式调用

通过 then() 方法返回的新 Promise 对象,可以继续链式调用其他 then() 方法或 catch() 方法。

示例代码:

const promise1 = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve('成功1');
  }, 1000);
});
const promise2 = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve('成功2');
  }, 1000);
});
promise1
  .then((result) => {
    console.log('第一步:', result);
    return promise2;
  })
  .then((result) => {
    console.log('第二步:', result);
  })
  .catch((error) => {
    console.log('失败:', error);
  });

then() 方法的异常处理

then() 方法中的回调函数抛出异常,可以通过链式调用 catch() 方法进行捕获。

示例代码:

const promise = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve('成功');
  }, 1000);
});
promise
  .then((result) => {
    console.log('成功:', result);
    throw new Error('出错了');
  })
  .catch((error) => {
    console.log('失败:', error);
  });

文章标题:JavaScrpt中的函数then是什么意思
分享URL:http://www.jxjierui.cn/article/coshiis.html