Bird
0
0

You want to run two async functions in parallel and handle errors separately. Which pattern is best?

hard📝 Application Q8 of 15
Node.js - Error Handling Patterns
You want to run two async functions in parallel and handle errors separately. Which pattern is best?
async function runTasks() {
  // Which code below correctly handles errors for both tasks?
}
Aconst [res1, res2] = await Promise.all([task1(), task2()]);
Bconst res1 = await task1().catch(e => console.error('Task1 error', e)); const res2 = await task2().catch(e => console.error('Task2 error', e));
Ctry { await task1(); await task2(); } catch (e) { console.error(e); }
Dtask1().then().catch(); task2().then().catch();
Step-by-Step Solution
Solution:
  1. Step 1: Understand parallel execution with error handling

    Running tasks in parallel and handling errors separately requires catching errors individually.
  2. Step 2: Evaluate options

    const res1 = await task1().catch(e => console.error('Task1 error', e)); const res2 = await task2().catch(e => console.error('Task2 error', e)); awaits each task with its own catch, allowing separate error handling; others either combine errors or lack awaits.
  3. Final Answer:

    const res1 = await task1().catch(e => console.error('Task1 error', e)); const res2 = await task2().catch(e => console.error('Task2 error', e)); -> Option B
  4. Quick Check:

    Parallel with separate error handling = B [OK]
Quick Trick: Use individual catch on awaited promises for separate error handling [OK]
Common Mistakes:
  • Using Promise.all without individual error handling
  • Wrapping both awaits in one try/catch
  • Not awaiting promises before catching

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Node.js Quizzes