Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

247
Views
why is the following code not returning sum of all the array elements?

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

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!