Error handling in Promise.all as a stream in async / wait syntax

I have some problems for handling multiple failures in parallel. How to handle deviation in async functions when we "wait in parallel".
Example:

function in_2_sec(number) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            reject('Error ' + number);
        }, 2000);
    }) 
}

async function f1() {
    try {
        let a = in_2_sec(3);
        let b = in_2_sec(30);
        return await a + await b; // awaiting in "parallel"
    } catch(err) {
        console.log('Error', err);
        return false;
    }
}

async function f2() {
    try {
        let a = await Promise.all([in_2_sec(3), in_2_sec(30)]);
        return a[0] + a[1];
    } catch(err) {
        console.log('Error', err);
        return false;
    }
}

// f1().then(console.log) // UnhandledPromiseRejectionWarning
// f2().then(console.log) // Nice


f1()create UnhandledPromiseRejectionWarningin node because the second deviation (b) is not processed.
f2()works fine, Promise.all()performs the trick, but how to do it f2()only with async / wait syntax, without Promise.all()?

+6
source share
2 answers

f2() , Promise.all() , f2() async/wait, Promise.all()?

. Promise.all! , . async/await promises - , then. Promise.all .

, Promise.all ( Promise .then), ( ).

+3

, , , - catch , , .

:

function noop() {
}

function markHandled(...promises) {
    promises.forEach(p => p && p.catch(noop));
}

:

async function f2() {
    let a, b;
    try {
        a = in_2_sec(3);
        b = in_2_sec(30);
        return await a + await b;
    } catch(err) {
        console.log('Error', err);
        markHandled(a, b);
        return false;
    }
}

, , , .

:

function in_2_sec(number) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            reject('Error ' + number);
        }, 2000);
    }) 
}

function noop() {
}

function markHandled(...promises) {
    promises.forEach(p => p && p.catch(noop));
}

async function f2() {
    let a, b;
    try {
        a = in_2_sec(3);
        b = in_2_sec(30);
        return await a + await b;
    } catch(err) {
        console.log('Error', err);
        markHandled(a, b);
        return false;
    }
}

f2().then(console.log);
Hide result
+2

Source: https://habr.com/ru/post/1016706/


All Articles