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

136
Visualizações
throwing UnhandledPromiseRejection even the code wrapped in try catch

I am getting UnhandledPromiseRejection error even I wrapped the code in try catch block I using await Prmomise.all together here

const express = require('express');
const app = express();
const port = 3003;

function testPromise(n) {
    return new Promise(async (res, rej) => {
        console.log(n);
        if (n > 10) {
            res(true);
        } else {
            setTimeout(() => {
                rej(n);;
            }, 1000)

        }
    });
}

function test2(n) {
    return new Promise(async (res, rej) => {
        console.log(n);
        if (n > 10) {
            res(true);
        } else {
            setTimeout(() => {
                rej(n);;
            }, 10000)

        }
    });
}
async function allCall(p) {
    await Promise.all(p);
}
app.get('/', async (req, res) => {
    try {
        let a = [];
        let b = [];

        a.push(testPromise(1));
        await test2(1);
        a.push(testPromise(12));
        // await Promise.all(a.map(m => m.then(() => { }).catch(err => { })));
        await Promise.all(a);
        res.send('Hello World!');
    } catch (err) {
        console.log('err');
        console.log(err);
        res.status(400).send('xxxxxxxxxx!')
    }

})

app.listen(port, () => {
    console.log(`Example app listening on port ${port}`)
})

I am not sure why it is throwing the error

[UnhandledPromiseRejection: This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch().

Please explain why and how to resolve this ?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You are getting this error because 2 promises are getting rejected but try/catch only handles one. The second promise is rejected but not handled.

1st rejection: a.push(testPromise(1));

2nd rejection: await test2(1);

NOTE:

  • Both the promises are started parallel.

  • try/catch only works with async/await, if you write promise inside try/catch it'll not be handled by the catch block.

    try {
        Promise.reject("Something")
    } catch (error) {
        console.log('Not here');
    }
    // Unhandled promise rejection
    

Explanation:

  1. When you push a promise to an array a.push(testPromise(1));, it starts execution and rejects after 1 second. It goes to catch.
  2. same time the second promise also started await test2(1); because you are not waiting for the first promise to resolve/reject. It'll get rejected after 1 second and not handled by the catch block. it'll go to catch only if you use with await. If you want to handle first rejection you have to use .catch. after 10 seconds second promise get rejected and handled by catch block.

Solution

const r = await testPromise(1);
await test2(1);

Another solution:

async (req, res) => {
  try {
    // a.push(testPromise(1));
    await test2(1);
    let a = [testPromise(1), testPromise(12)];
    await Promise.all(a);
    console.log("done");
  } catch (err) {
    console.log("err");
    console.log(err);
  }
};
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