Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add to existing Promises.all array from catch of Promise

I am having a piece of code where I am adding a few Async operations to a promise array and calling Promise.all to resolve all of them and await the result. I have an expectation to check for failure of second operation and perform operation one from its catch block if it so happens. If I am attaching a catch block to one of the promises of this array and performing an async operation can I add to the same promise array or am I better off to await this operation separately.

const promises = [];
promises.push(performAsync1(record))
promises.push(performAsync2().catch(() =>
   console.error("Async2 Failed");
   promises.push(performAsync1(failedRecord));
}
const responses = await Promise.all(promises);
like image 852
HariJustForFun Avatar asked Dec 02 '25 08:12

HariJustForFun


1 Answers

This may get closed for being "primarily" opinion based, but I would assign that performAsync2 operation/retry combo to a variable.

const performAsync2Retrying = performAsync2(record).catch(()=> performAsync1(record))
const promises = []
promises.push(performAsync1(record))
promises.push(performAsync2Retrying)
const responses = await Promise.all(promises)

This makes the construction of your promises array easy to read with a single responsibility.

Writing this in a more modern idiom makes the goodnes even clearer:

const performAsync2Retrying = performAsync2(record).catch(()=> performAsync1(record))
const responses = await Promise.all([performAsync1(record),
    performAsync2Retrying])

But what I'd really want to do here is to avoid introducing the extra name with a helper function that executes a second function if the first fails (which could be elaborated on to handle multiple arguments)

const retryWith = (f1, f2, _in) => f1(_in).catch(_=>f2(_in))

const responses = await Promise.all([
    performAsync1(record),
    retryWith(performAsync2, performAsync1, record)
 ])

And then I never need to think about handling this scenario again.

like image 74
Robert Moskal Avatar answered Dec 03 '25 23:12

Robert Moskal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!