下面是代码,我想返回所有数组元素的总和,为什么它不起作用。我知道我们不需要 Promise 来实现这一目标,但我想知道如何使用 Promise 来实现这一点。
const arr = [1, 5, 7, 8];
function sumPromise(a, b) {
return new Promise((res) => {
setTimeout(() => {
res(a + b);
}, 1000);
});
}
let res = arr.reduce(sumPromise);
res.then((a) => console.log(a));
输出:[对象 promise ]8
最佳答案
希望这会有所帮助
const arr = [1, 5, 7, 8];
function sumPromise(a, b) {
return new Promise((res) => {
setTimeout(() => {
a.then(item => res(item + b))
}, 1000);
});
}
let res = arr.reduce(sumPromise, Promise.resolve(0));
res.then((a) => console.log(a));
不改变 sumPromise
const arr = [1, 5, 7, 8];
function sumPromise(a, b) {
return new Promise((res) => {
setTimeout(() => {
res(a + b);
}, 1000);
});
}
let res = arr.reduce(
(a, b) => a.then(item => sumPromise(item, b)),
Promise.resolve(0)
);
res.then(console.log);
关于javascript - 为什么以下代码不返回所有数组元素的总和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72963501/