在promise中,多个then如何传值

在 JavaScript 中,Promise 的多个 .then()链式调用 的,值可以通过返回值 的方式,在多个 .then() 之间传递。这是 Promise 链式调用的核心机制。


基本原理:每个 then 接收上一个 then 的返回值

javascript 复制代码
new Promise((resolve, reject) => {
  resolve(10); // 初始值
})
  .then((value) => {
    console.log("第一个 then 收到:", value); // 10
    return value * 2;
  })
  .then((value) => {
    console.log("第二个 then 收到:", value); // 20
    return value + 5;
  })
  .then((value) => {
    console.log("第三个 then 收到:", value); // 25
  });

输出:

复制代码
第一个 then 收到: 10
第二个 then 收到: 20
第三个 then 收到: 25

每个 .then() 的返回值会作为下一个 .then() 的输入参数。


如果某个 then 返回的是 Promise?

如果某个 .then() 返回一个新的 Promise,那么下一个 .then() 会在该 Promise 成功解决(fulfilled) 后执行,并接收到它的 resolve 值。

javascript 复制代码
new Promise((resolve) => resolve(10))
  .then((value) => {
    console.log("第一个 then:", value); // 10
    return new Promise((resolve) => setTimeout(resolve, 1000, value * 2));
  })
  .then((value) => {
    console.log("第二个 then(1秒后):", value); // 20
  });

多个异步操作串行执行(链式传值)

你可以利用这种特性来串行处理多个异步任务:

javascript 复制代码
function step1(value) {
  return new Promise((resolve) => {
    setTimeout(() => {
      console.log("Step 1:", value);
      resolve(value + 1);
    }, 1000);
  });
}

function step2(value) {
  return new Promise((resolve) => {
    setTimeout(() => {
      console.log("Step 2:", value);
      resolve(value * 2);
    }, 1000);
  });
}

function step3(value) {
  return new Promise((resolve) => {
    setTimeout(() => {
      console.log("Step 3:", value);
      resolve(value - 5);
    }, 1000);
  });
}

step1(5)
  .then(step2)
  .then(step3)
  .then((finalResult) => {
    console.log("最终结果:", finalResult); // (5+1)*2 -5 = 7
  });

错误处理:catch 捕获链中任意错误

javascript 复制代码
Promise.resolve(10)
  .then((val) => {
    console.log(val);
    throw new Error("出错了!");
  })
  .then(() => {
    console.log("不会执行");
  })
  .catch((err) => {
    console.error("捕获错误:", err.message);
  });

小结:如何传值?

场景 如何传值
同步返回值 直接 return value
异步返回值 return new Promise(...)
终止链或跳转 抛出异常 throw error 或返回 rejected Promise
多个值传递? 返回对象或数组,如 return { a, b }

示例:带多个值传递的 Promise 链

javascript 复制代码
Promise.resolve({ name: "Alice", age: 10 })
  .then((person) => {
    person.age += 1;
    return person;
  })
  .then((person) => {
    console.log(`${person.name} 现在 ${person.age} 岁了`);
  });

如果你需要更复杂的流程控制,比如并行、条件分支等,也可以结合 Promise.allasync/await 来实现。

相关推荐
沐知全栈开发1 天前
ionic 手势事件详解
开发语言
这个DBA有点耶1 天前
分组排名不用窗口函数?那你还在写几十行的子查询
前端·代码规范
ZhiqianXia1 天前
《The Design of Design》阅读笔记
前端·笔记·microsoft
有马贵将1 天前
【5】微前端知识点总结
前端·架构
mkae1 天前
eBPF高性能版fail2ban
前端
lsx2024061 天前
Bootstrap 按钮
开发语言
_柴富自由1 天前
前端项目国际化解决方案
前端
isixe1 天前
Uniapp 监听回到前台并全局唯一弹窗
前端
神仙别闹1 天前
基于 Python 实现 BERT 的情感分析模型
开发语言·python·bert
禾叙_1 天前
【langchain4j】结构化输出(六)
java·开发语言