简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM