I would want to execute in parallel two API calls inside my thunk. However, I need to properly handle the errors. I have prepared simplified version of my async functions. Sections I want to parallelize are commented.
async function addCredentialA() {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (Math.random() < 0.5)
return resolve({status: '200'})
else
return reject({status: '500'})
}, 1000)
});
}
async function addCredentialB() {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (Math.random() < 0.3)
return resolve({status: '200'})
else
return reject({status: '500'})
}, 2000)
});
}
async function addCredentials(sendRequestA: boolean, sendRequestB: boolean) {
try {
// This should be parallel
if (sendRequestA) {
try {
await addCredentialA()
console.log('Successfully added credential A')
} catch (e) {
console.log('Something wrong with credential A', e)
throw e
}
}
// This should be parallel
if (sendRequestB) {
try {
await addCredentialB()
console.log('Successfully added credential B')
} catch (e) {
console.log('Something wrong with credential B', e)
throw e
}
}
console.log('Succesfully added two credentials')
} catch (e) {
console.log('There was problem with adding credentials')
console.log(e)
}
}
addCredentials(true, true)