JavaScript

Lesson 07

Promise concurrency

Run independent async work together instead of waiting one request at a time.

Good Code

review-sidebar.js
async function loadReviewSidebar(pullRequestId) {
  // Independent requests start together and fail as one group.
  const [checks, comments, reviewers] = await Promise.all([
    fetchChecks(pullRequestId),
    fetchComments(pullRequestId),
    fetchReviewers(pullRequestId),
  ]);

  return { checks, comments, reviewers };
}

Bad Code

review-sidebar.js
async function loadReviewSidebar(pullRequestId) {
  // Sequential awaits add latency without a data dependency.
  const checks = await fetchChecks(pullRequestId);
  const comments = await fetchComments(pullRequestId);
  const reviewers = await fetchReviewers(pullRequestId);

  return { checks, comments, reviewers };
}

Review Notes

What to review

Good Code

The good version starts three independent requests together and waits for the shared result once.

Bad Code

The bad version makes each request wait for the previous one even though none of them uses the previous result, adding avoidable latency to the page.

Takeaways

  • Use Promise.all for independent required work and reserve sequential awaits for true dependencies.