3

I am processing multiple records using async/await and for parallel using Promise.all see my sample code below

  let results = [100,200]
  let promises = results.map(async record => {
   try { 
     return await processingRecords(record);  
   } catch (err) {
   }
  });
  await Promise.all(promises);

async function processingRecords(item) {
 switch (item['#type']) {
    case 'case1':
        await Request1(item)
        await Request2(item)
    break
    case 'case2':
        await Request3(item)
 }
}

But the problem is if Request1 is getting any error I can't catch error from Request2 call how to handle error from both calls

2
  • Solution depends largely on where you want to do the error handling. Overall program architecture/design may dictate that it be done in processingRecords() or in its caller(s). Commented Jun 24, 2019 at 15:33
  • If Request1() throws an error, Request2() is never called so how would you expect to be able to handle an error from it? Commented Jun 24, 2019 at 16:44

1 Answer 1

1

You can to do a few things here to keep the calls going. Catching errors around the await statements and returning the combined result of Request1 and Request2 will work:

For example:

async function processingRecords(item) {
    switch (item['#type']) {
        case 'case1':
            let combinedResult = {};
            try { 
                combinedResult.Request1Result = await Request1(item);
            } catch (err) {
                combinedResult.Request1Error = err;
            }
            try { 
                combinedResult.Request2Result = await Request2(item);
            } catch (err) {
                combinedResult.Request2Error = err;
            }
            // Keep the promise chain intact.;
            return combinedResult;
        case 'case2':
            return await Request3(item);
        }
}


let promises = results.map(async record => {
    try { 
        return await processingRecords(record);  
    } catch (err) {
        // Keep the promise chain intact by throwing err here.
        throw err;
    }
});

let overallResult = await Promise.all(promises);
console.log(overallResult);
Sign up to request clarification or add additional context in comments.

1 Comment

Case1 guarantees that the promise returned by processingRecords(record) will follow its success path. Error(s) bundled into an object are effectively data. The caller would need to jump through hoops in order to handle them. That's not, in itself, wrong but bear in mind that case1 and case2 will behave differently.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.