JavaScript Promise 多链式调用与核心 API 原理详解

作者:半夏时间:2026-10-26 12:50:43浏览:112

本文深入解析 JavaScript Promise 的核心机制,包括多次调用 then 方法的返回值处理逻辑、Promise.resolve 返回具有 then 方法对象时的微任务延迟现象,以及 Promise.all、allSettled 和 race 在错误处理与结果获取上的具体差异与适用场景。

一、为什么一个promise可以调用多个.then方法

如下面的:

const promise = new Promise((resolve, reject) => {
  resolve("hahaha")
})
// 1.同一个Promise可以被多次调用then方法
// 当我们的resolve方法被回调时, 所有的then方法传入的回调函数都会被调用
promise.then(res => {
  console.log("res1:", res)    //hahaha
})
promise.then(res => {
  console.log("res2:", res)    //hahaha
})
promise.then(res => {
  console.log("res3:", res)    //hahaha
})

答案:

  • 当 then 内的回调函数不返回任何值时,默认返回当前 Promise 实例本身。
  • 当 then 内的回调函数返回一个 Promise 对象时,该 Promise 的状态将决定后续链式调用的结果。
  • 当 then 内的回调函数返回一个普通值(如数值、字符串、普通对象或 undefined)时,该值会被封装为一个新的 Promise 的 resolve 值。

二、什么是Promise.resolve()

Promise.resolve() 用于创建一个状态为 fulfilled(已解决)的 Promise 对象。

Promise.resolve()
// 等同于
new Promise((resolve)=>{resolve()})

为什么会有下面的执行结果? 感觉十分异常

Promise.resolve().then(() => {
  console.log(0);
  return Promise.resolve(4)
}).then(res => {
  console.log(res)
})
Promise.resolve().then(() => {
  console.log(1);
}).then(() => {
  console.log(2);
}).then(() => {
  console.log(3);
}).then(() => {
  console.log(5);
}).then(() =>{
  console.log(6);
})
// 0,1,2,3,4,5,6
(
  async function() {
    return Promise.resolve()
  }
)().then(()=>{
  console.log(1)
})
new Promise((resolve) => {
  resolve()
}).then(()=>{
  console.log(2)
}).then(()=>{
  console.log(3)
})
/// 2 3 1

答案:

如果 Promise.resolve() 返回的对象具有可调用的 then 方法,引擎会在微任务队列中插入一个名为 NewPromiseResolveThenableJob 的任务。该任务会执行这个 then 方法,由于执行过程涉及异步操作,因此比直接返回普通值慢了一步;若该 then 方法本身来自 Promise,则因异步特性又慢了一步,总共导致执行延迟两拍。

参考

三、Promise.all缺陷和Promise.allSettled

Promise.all() 的缺陷

其中任意一个 promise 被 reject ,Promise.all 就会立即被 reject ,不在执行then。

数组中其它未执行完的 promise 依然是在执行的,但是Promise.all 没有返回它们的结果,同时Promise.all 没有采取任何措施来取消它们的执行。

Promise.allSettled()

Promise.allSettled() 可以获取数组中每个 promise 的结果,无论成功或失败

只有then方法 所有结果都会在then中体现

注意

彼此相互依赖,一个失败全部失效(全无或全有)用 Promise.all ;相互独立,获取每个结果用 Promise.allSettled

四、Promise.race() 使用

多个promise执行,最快的执行Promise.race()的then或者catch

里面的promise依旧会执行

const promise1 = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve('Promise 1 resolved');
      console.log(0)
  }, 1000);
});
const promise2 = new Promise((resolve, reject) => {
  setTimeout(() => {
      console.log(2)
    resolve('Promise 2 resolved');
  }, 2000);
});
Promise.race([promise1, promise2]).then(result => {
  console.log(result); // "Promise 1 resolved"
});
// 0
//Promise 1 resolved
//2

到此这篇关于JavaScript promise的使用和原理分析的文章就介绍到这了,更多相关JS promise内容请搜索本站以前的文章或继续浏览下面的相关文章希望大家以后多多支持本站!

作者最新文章