关于 promise reduce执行顺序?-灵析社区

刘传疯子

## 关于 promise reduce执行顺序 function runPromiseInSequence(arr, input) { return arr.reduce( (promiseChain, currentFunction) => promiseChain.then(currentFunction), Promise.resolve(input), ); } // Promise 函数 1 function p1(a) { return new Promise((resolve, reject) => { resolve(a * 5); }); } // Promise 函数 2 function p2(a) { return new Promise((resolve, reject) => { resolve(a * 2); }); } // 函数 3——将由 `.then()` 包装在已解决的 Promise 中 function f3(a) { return a * 3; } // Promise 函数 4 function p4(a) { return new Promise((resolve, reject) => { resolve(a * 4); }); } const promiseArr = [p1, p2, f3, p4]; runPromiseInSequence(promiseArr, 10).then(console.log); Promise.resolve(1).then(2).then(console.log); // p1---1 Promise.reject(1).then(2, 2).then(console.log, console.log); //p1---1 //控制台: //1 //1 //1200 请高手解释下为何p1和p2为什么都是打印1,p1和p2都在runPromiseInSequence之前执行 这是我尝试修改后的代码, function runPromiseInSequence(arr, input) { // 使用reduce方法,将arr中的函数按照顺序执行,并将结果返回 return arr.reduce( // 传入一个回调函数,该回调函数接收两个参数:promiseChain和currentFunction,promiseChain是上一次函数的执行结果,currentFunction是arr中的当前函数 (promiseChain, currentFunction) => promiseChain.then((res)=>{ console.log(res,'res'); return currentFunction(res) }), // 将input作为初始值,并将其传入Promise.resolve()方法,将结果作为promiseChain的值 Promise.resolve(input), ); } // Promise 函数 1 function p1(a) { return new Promise((resolve, reject) => { resolve(a * 5); }); } const promiseArr = [p1]; // console.log(runPromiseInSequence(promiseArr, 10)); runPromiseInSequence(promiseArr, 10).then((res)=>{ console.log(res,'fn'); }); // 50 Promise.resolve(1).then(2).then((res)=>{ console.log(res,'p1') }); Promise.reject(1).then(2, 2).then( console.log, console.log); 看起来还是比较吃力,求大佬帮我解析一下,问了chatgpt回答的不正确

阅读量:11

点赞量:0

问AI
问题1:为何p1和p2为什么都是打印1楼上的大佬已经给出了原因, 至于问题2:p1和p2都在runPromiseInSequence之前执行;这是由于同步代码、异步代码的微任务队列先后执行顺序;arr.reduce同步代码的执行相当于执行Promise.resolve(10).then(p1).then(p2).then(f3).then(p4); 而promise.then的程序会被加入微任务队列中执行,所以会和下面的Promise.resolve(1).then(2).then(console.log); Promise.reject(1).then(2, 2).then(console.log, console.log); 中的.then程序交替进入微任务队列执行。同时其中return new Promise((resolve,reject)=>{resolve()})还会带来另一个问题,可以参考这位大佬的回复 "image.png" (https://wmlx-new-image.oss-cn-shanghai.aliyuncs.com/images/20241028/a1f8a922a65ed21cf73dc32653035745.png)