JavaScript 中 then 方法的使用方式

2025-01-09 20:12:45   小编

JavaScript 中 then 方法的使用方式

在 JavaScript 异步编程的世界里,then 方法扮演着至关重要的角色。它与 Promise 对象紧密相连,为处理异步操作的结果提供了一种优雅的方式。

Promise 是一种异步操作的最终完成或失败,并返回其结果的对象。而 then 方法则用于处理 Promise 成功的情况。当一个 Promise 被 resolve(解决)时,then 方法中的回调函数会被执行,该回调函数接收 Promise 成功返回的值作为参数。

基本的使用形式如下:

const promise = new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve('操作成功');
    }, 1000);
});

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

在上述代码中,我们创建了一个 Promise,它在 1 秒后被 resolve 并返回一个字符串。then 方法捕获到这个成功结果并打印出来。

then 方法还支持链式调用。这意味着我们可以在一个 then 方法后接着调用另一个 then 方法,每个 then 方法处理上一个 then 方法返回的结果。例如:

const promise = new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve(5);
    }, 1000);
});

promise
  .then((number) => number * 2)
  .then((doubledNumber) => doubledNumber + 3)
  .then((finalResult) => console.log(finalResult)); 

这里,第一个 then 方法将 Promise 返回的数字乘以 2,第二个 then 方法再将结果加 3,最后一个 then 方法打印出最终结果。

then 方法还可以接收第二个回调函数作为参数,用于处理 Promise 失败的情况。不过,更推荐使用 catch 方法来专门处理 Promise 的拒绝状态,这样代码结构会更清晰。

const promise = new Promise((resolve, reject) => {
    setTimeout(() => {
        reject('操作失败');
    }, 1000);
});

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

// 推荐使用 catch 方法
promise.catch((error) => {
    console.log(error); 
});

掌握 then 方法的使用方式,能让我们在处理异步操作时更加得心应手,编写出更高效、更易读的 JavaScript 代码。无论是简单的异步任务,还是复杂的异步操作链,then 方法都能发挥其重要作用。

TAGS: JavaScript 使用方式 JavaScript编程 then方法

欢迎使用万千站长工具!

Welcome to www.zzTool.com