2 回答
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));
// ^^^^^^
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));
添加回答
举报