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

143
Visualizações
Catching promise errors from a loop

I need to call multiple promises inside a for loop, but it gives me unhandled promise exception during each run. The way to solve this is to return the second promise, this way the last catch would be executed and it would work without errors, but - second and more iterations would not be executed.

const doFirstThing = () => {
    return new Promise((resolve, reject) => {
        setTimeout(() => (resolve(['a', 'b', 'c'])), 1000);
    });
}

const doSecondThing = () => {
    return new Promise((resolve, reject) => {
        setTimeout(() => (reject('test')), 500); // reject here
    });
}

doFirstThing()
.then(results => {
    results.forEach(result => {
        doSecondThing(result)
        .then(() => console.log(result, 'done'));
    });
})
.catch(error => console.log(error));

How can I deal with this?

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

To prevent unhandled promise exception chain .catch() to lat .then(); substitute using Promise.all() and .map() for .forEach()

const doFirstThing = () => {
    return new Promise((resolve, reject) => {
        setTimeout(() => (resolve(['a', 'b', 'c'])), 1000);
    })
}

const doSecondThing = (r) => {
    return new Promise((resolve, reject) => {
        setTimeout(() => (reject('test')), 500); // reject here
    })
}

doFirstThing()
.then(results => {
    return Promise.all(results.map(result => {
        return doSecondThing(result)
    }));
})
.then((result) => console.log(result, 'done'))
.catch(error => console.log(`err:${error}`));

over 4 years ago · Santiago Trujillo 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