Home > Net >  why is the following code not returning sum of all the array elements?
why is the following code not returning sum of all the array elements?

Time:07-13

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

CodePudding user response:

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);

CodePudding user response:

let total = 0;
const arr = [1, 5, 7, 8];

function sumPromise(a, b) {
    return new Promise((res) => {
        setTimeout(() => {
            res(total = total   b);
        }, 1000);
    });
}
let res = arr.reduce(sumPromise, total);
res.then((a) => console.log(total));

  • Related