0

I have the promise in function2 which is rejected and added into the array of promises in function1. The code ends with UnhandledPromiseRejection. Can you please help me to understand why the promise is not successfully returned from function1 and caught in test function?

const sleep = require("sleep-promise");

function function1() {
    const promises = [];
    promises.push(function2());
    return sleep(1000).then(() => {
        return Promise.all(promises)
    });
}

function function2() {
    return new Promise((resolve, reject) => {
        reject("failed");
    })
}

async function test() {
    try {
        await function1();
    } catch (e) {
        console.log(e);
    }
}

test();

output:

[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(). The promise rejected with the reason "failed".]
Jaroslav
  • 19
  • 4
  • A promise that rejects must be caught in at least one place *at the moment it rejects*, or there'll be an unhandled rejection. Your `promises.push(function2());` doesn't handle it immediately. (You've also forgotten to return the sleep call - `function1` returns `undefined`) – CertainPerformance Oct 15 '22 at 19:32
  • Is there a way how to accumulate list of promises and evaluate their state later on? (thanks, I've fixed the missing return in the original post) – Jaroslav Oct 15 '22 at 19:47
  • Evaluate, sure - but you must catch *somewhere* immediately – CertainPerformance Oct 15 '22 at 19:48
  • Got it and `promises.push(function2().catch(() => promiseRejected = true));` is how would you identify a rejection? – Jaroslav Oct 15 '22 at 19:58
  • Only if you actually use `promiseRejected` somewhere - an empty block would make more sense otherwise – CertainPerformance Oct 15 '22 at 20:04

0 Answers0