Skip to main content

Command Palette

Search for a command to run...

JavaScript Promises With Team 7

Updated
β€’5 min readβ€’View as Markdown
JavaScript Promises With Team 7

Kakashi assigns Team 7 with a dangerous mission.
Mission: Retreive a scroll from an enemy territory.

const team7Mission = new Promise((resolve, reject) => {
  // Mission in progress...
  setTimeout(() => {
    resolve("Mission Complete! Scroll Retrieved!"); // Success
  }, 3000);
});

The Mission Status: Promise State

  1. Mission is in Progress: Promise Pending State
    Naruto, Sasuke, and Sakura are on their way to get the scroll.
console.log("Mission Status: PENDING...");
// Team 7 is in the enemy base
  1. Mission Successful: Promise Resolved
    Team 7 fought the enemies, got the scroll, and came back in one piece.
team7Mission.then((result) => {
  console.log(result); // "Mission Complete! Scroll Retrieved!"
});
  1. Mission Failed: Rejected (In case they failed)
    They got captured.
team7Mission.catch((error) => {
  console.log(error); // "Mission Failed!!!"
});

Battle Scenerios: Static Methods In Promises

  1. Team 7 Never Abandons Anyone: Promise.all()
    Naruto's unsaid rule: Nobody can be left behind. so they wait for all members to complete their tasks.
    In this case even if one member fails the whole team fails.
const narutoTask = new Promise((resolve) => {
  setTimeout(() => resolve("Naruto defeated 5 enemies"), 5000);
});

const sasukeTask = new Promise((resolve) => {
  setTimeout(() => resolve("Sasuke defeated 5 enemies"), 5000);
});

const sakuraTask = new Promise((resolve) => {
  setTimeout(() => resolve("Sakura did something useful hopefully"), 4000);
});

Promise.all([narutoTask, sasukeTask, sakuraTask])
  .then((results) => {
    console.log("Team 7 Report:");
    console.log(results);
  });
// Output As Expected
    // [
    //   "Naruto defeated 5 enemies",
    //   "Sasuke defeated 3 enemies", 
    //   "Sakura did something useful hopefully"
    // ]
// if any promise is rejected then everything fails.
  1. The Race Between Naruto And Sasuke: Promise.race()
    Kakashi announces a race: naruto and sasuke compete as usual (whoever finishes first wins) regardless of mission status.

The Race() doesn't care about success or failure
it's like whoever comes first regardless of mission status(successful or failed) wins.

const narutoGetsHurt = new Promise((resolve,reject) => {
  setTimeout(() => reject("Naruto got hurt!"), 2000);
});

const sasukeFinishes = new Promise((resolve) => {
  setTimeout(() => resolve("Sasuke finished!"), 5000);
});

Promise.race([narutoGetsHurt, sasukeFinishes])
  .catch((error) => {
    console.log(error); // "Naruto got hurt!" (first to complete, even if failure)
  });
  1. Naruto's Last-Minute Victory: Promise.any()
    Three teams are competing in an exam. Naruto's team finishes LAST but succeeds. Because, the mission was to complete the mission successfully. other two teams thought it was race() where just finish regardless of mission status.
const gaaraTeam= new Promise((resolve, reject) => {
  setTimeout(() => reject("Team 1 failed!"), 2000);
});

const shikamaruTeam= new Promise((resolve, reject) => {
  setTimeout(() => reject("Team 2 failed!"), 3000);
});

const narutoTeam = new Promise((resolve) => {
  setTimeout(() => resolve("Team 7 PASSED! Naruto did it!"), 5000);
});

Promise.any([team1Exam, team2Exam, narutoTeam])
  .then((result) => {
    console.log(result); // "Naruto did it!"
    // We don't care that they finished last, only that they succeeded
  });

Difference Between Race() and any() is that any() ignores failures and wait for first promise to be success and returns it.

  1. Hokage's Report Card: Promise.allSetteled()
    Hokage wants a full report on ALL team Members, who failed who succeeded without skipping.

In allSetteled(): Each element has status and either value or reason.

const narutoMission = new Promise((resolve) => {
  resolve("Naruto: Completed training");
});

const sasukeMission = new Promise((resolve, reject) => {
  reject("Sasuke: Abandoned training");
});

const sakuraMission = new Promise((resolve) => {
  resolve("Sakura: Did Something");
});

Promise.allSettled([narutoMission, sasukeMission, sakuraMission])
  .then((results) => {
    console.log("Hokage's Report:");
    console.log(results);
    // [
    //   { status: 'fulfilled', value: 'Naruto: Completed training βœ“' },
    //   { status: 'rejected', reason: 'Sasuke: Abandoned training βœ—' },
    //   { status: 'fulfilled', value: 'Sakura: Completed mission βœ“' }
    // ]
  });
  1. We Already Know Team 7 Succeeded: Promise.resolve()
    We don't need to wait, we already know that Team 7 will succeed because they have both Naruto and Sasuke.
Promise.resolve("Team 7 is legendary! Mission guaranteed success!")
  .then((result) => {
    console.log(result); // "Team 7 will succeed no matter what"
  });
  1. Promise.reject() - Sakura Alone (Mission Failed)
    Time when sakura wanted to do all the mission alone, we know the outcome... she failed (faster than minato). we already know the outcome that it will fail.
Promise.reject("Sakura wanted to go alone! Mission Failed!")
  .catch((error) => {
    console.log(error); // "Sakura wanted to go alone! Mission Failed!"
  });
  1. Sasuke Retreival Arc: Promise.withResolvers()
    Team 7 cannot rescue Sasuke alone, as a result they need external support form other teams (Team 8, Team 10). The other teams have their own mission status.

withResolvers(), other team have their own control when to resolve not just Team 7 alone.

const { promise, resolve, reject } = Promise.withResolvers();

console.log("Team 7 called backup teams!");

setTimeout(() => {
  const backupTeams = "Shikamaru, Choji, Kiba, Hinata arrived to help!";
  resolve(`Sasuke retrieval in progress with help: ${backupTeams}`);
}, 2000);

promise.then((result) => {
  console.log(result);
//output
  // "Sasuke retrieval in progress with help: Shikamaru, Choji, Kiba, Hinata arrived to help!"
});

Conclusion

That was a quick analogy with our legendry team 7, with their ongoing missions we learnt about promises on the go. A link to programming that i never thought can be built... but here we are learning promises with Naruto.

References:

  1. Mdn

Dattebayo πŸ₯·