#StackBounty: #javascript #concurrency #async-await #try-catch Awaiting multiple promises inside an async function with try catch throw…

Bounty: 50

I can’t understand why the following code doesn’t throw:

const main = async () => {

    const Stop = (time) => new Promise((resolve) => setTimeout(resolve, time))

    try {
        const p1 = Stop(500).then(() => { throw new Error('Error ocurred') })
        const p2 = Stop(1000)

        await p1
        await p2
    } catch (err) {
        console.log('error catched')
    }
}

main()

But whenever I invert the order of p1 and p2 promises, like this:

const main = async () => {

    const Stop = (time) => new Promise((resolve) => setTimeout(resolve, time))

    try {
        const p1 = Stop(500).then(() => { throw new Error('Error ocurred') })
        const p2 = Stop(1000)

        await p2
        await p1
    } catch (err) {
        console.log('error catched')
    }
}

main()

Then an uncaught exception is thrown. I suppose that doing concurrent tasks like that without .catch functions is dangerous, but I thought the async code within a try catch would never throw.

Why isn’t this the case, exactly?


Get this bounty!!!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.