Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

257
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda