为了账号安全,请及时绑定邮箱和手机立即绑定

如何使用 Array.reduce() 在给定的 JavaScript 代码中解析 Promise?

如何使用 Array.reduce() 在给定的 JavaScript 代码中解析 Promise?

白衣非少年 2023-03-10 14:56:46
请参考以下JavaScript代码:var arr = [30, 40, 10, 50, 20];var fun = function(n) {  console.log("Before Promise => n: " + n);  return new Promise(resolve => {    console.log("After Promise => n: " + n);    setTimeout(() => {      console.log("Promise Resolved => n: " + n);      resolve(0);    }, n * 30);  });}arr.reduce((p, v) => p.then(fun(v)), Promise.resolve(0));1.如果我错了请纠正我,Array.reduce()将上面的内容减少为以下Promise链:Promise.resolve(0).then(fun(30)).then(fun(40)).then(fun(10)).then(fun(50)).then(fun(20)).2.为什么输出不是如下:Promise Resolved => n: 30Promise Resolved => n: 40Promise Resolved => n: 10Promise Resolved => n: 50Promise Resolved => n: 203.n*30如果我用固定时间更改,为什么输出如上500?
查看完整描述

2 回答

?
一只名叫tom的猫

TA贡献1906条经验 获得超2个赞

.then接受一个函数作为参数,但你正在做:


p.then(fun(v))

这会fun 立即调用,无需等待p解决,并将返回的 Promise 传递给.then。就像做


Promise.then(Promise.resolve(6))

         //  ^^^ but .then only accepts a function as a parameter

这没有意义。


更改为回调,在调用时调用fun并返回fun的 Promise:


var arr = [30, 40, 10, 50, 20];

var fun = function(n) {

    console.log("Before Promise => n: " + n);

    return new Promise(resolve => {

        console.log("After Promise => n: " + n);

        setTimeout(() => {

            console.log("Promise Resolved => n: " + n);

            resolve(0);

        }, n*30);

    });

}

arr.reduce((p, v) => p.then(() => fun(v)), Promise.resolve(0));

//                          ^^^^^^


查看完整回答
反对 回复 2023-03-10
?
Cats萌萌

TA贡献1805条经验 获得超9个赞

Array.reduce()将减少上述内容,如下 Promise 链


是的。


为什么输出不符合预期?


因为承诺“链条”断了。为了正确链接,您需要将回调函数传递给then:


Promise.resolve(0).then(() => fun(30)).then(() => fun(40)).then(() => fun(10)).then(() => fun(50)).then(() => fun(20));

//                      ^^^^^               ^^^^^               ^^^^^               ^^^^^               ^^^^^

在你的减速器中做同样的事情:


arr.reduce((p, v) => p.then(() => fun(v)), Promise.resolve(0));


查看完整回答
反对 回复 2023-03-10
  • 2 回答
  • 0 关注
  • 83 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信