Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

133
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda