Below is the code, I want to return the sum of all the array elements, why is it not working. I know we don’t need the Promise to achieve that but I would like to know how it can be done with a 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));
output:[object Promise]8
Advertisement
Answer
I hope this will help
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));
Without changing 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);