DEV Community

Tanvir Azad
Tanvir Azad

Posted on

Promise.all(): The Case of the Missing Tuna

Scene: Catland Central Police Station

Detective Oreo is sipping catnip tea when suddenly—an emergency call comes in:

“THE TUNA IS MISSING FROM THE FRIDGE!”

Oreo slams down his tea. “Not on my watch.”

To solve the case, he must gather three critical clues from different sources:

  1. Pawprint Analysis
  2. Scent Trail Report
  3. Surveillance Footage

Each report takes time, and they are all asynchronous.


Oreo the Async Detective (Enter: Promise.all)

Here’s how it looks in code:

// Simulated async clue fetchers
function getPawprintAnalysis() {
  return new Promise(resolve =>
    setTimeout(() => resolve("Pawprints match: Garfield"), 1000)
  );
}

function getScentTrailReport() {
  return new Promise(resolve =>
    setTimeout(() => resolve("Scent trail leads to the litter box"), 2000)
  );
}

function getSurveillanceFootage() {
  return new Promise(resolve =>
    setTimeout(() => resolve("Garfield spotted at 2AM near fridge"), 1500)
  );
}
Enter fullscreen mode Exit fullscreen mode

Oreo doesn’t want to wait one by one for each clue. So, he does the smart thing:

Promise.all([
  getPawprintAnalysis(),
  getScentTrailReport(),
  getSurveillanceFootage()
]).then(([pawprints, scent, footage]) => {
  console.log("Case Clues:");
  console.log(pawprints);
  console.log(scent);
  console.log(footage);
  console.log("Oreo concludes: It was Garfield! Case closed.");
});
Enter fullscreen mode Exit fullscreen mode

What Promise.all() Does

  • Runs all clue fetches in parallel
  • Waits for ALL to finish
  • Returns an array of results
  • If any one fails, the whole thing fails (Oreo yells: “Abort!”)

What If One Clue Fails?

Let’s say the surveillance camera was unplugged by a raccoon:

function getSurveillanceFootage() {
  return new Promise((_, reject) =>
    setTimeout(() => reject("Camera offline! Raccoon sabotage suspected."), 1500)
  );
}

Promise.all([
  getPawprintAnalysis(),
  getScentTrailReport(),
  getSurveillanceFootage()
]).then(clues => {
  console.log(clues);
}).catch(error => {
  console.error("Investigation failed:", error);
  console.log("Oreo: ‘Back to square one... but I’ll get that tuna thief.’");
});
Enter fullscreen mode Exit fullscreen mode

Summary Table: Promise.all()

Feature Description
Purpose Run multiple promises in parallel
Result Resolves with array of all results
Failure If one fails, the entire Promise.all() fails
Ideal for When all results are required to proceed

Detective Oreo Says:

“If you're solving a crime and need all the clues before pouncing, use Promise.all()—the purr-fect tool for the job.”

Top comments (0)