The Journey of #100DaysOfCode (Baqer_Qabalan)

Imagine you order a pizza, so the process can be broken into several steps: You call the bakery and place an order for a pizza, then the bakery confirms your order and gives you an estimated delivery time. At this point, a promise is created and it is in the “pending” state. During this time, you’re waiting for the pizza to be delivered, and you don’t know if it will arrive on time, be delayed, or if there might be an issue with the bakery. So, the promise is still in the “pending” state. Now, there are two cases: if the pizza arrives (order is fulfilled), the promise is fulfilled. If there is an issue with the bakery and the pizza doesn’t arrive (order is rejected), the promise is rejected.

In this code:
A function called orderPizza is created that returns a new Promise, so this promise starts in the “pending” state.
The setTimeout function is used to simulate the wait time for the pizza delivery. This represents the period during which the promise is pending.
After 2 seconds, a random boolean value called isPizzaDelivered determines whether the pizza is delivered or not:
If the boolean is true, the promise is resolved by calling resolve, so the promise is moved to the “fulfilled” state.
If the boolean is false, the promise is rejected by calling reject, and the promise is moved to the “rejected” state.
The then method is used to handle the case when the promise is fulfilled, while the catch method is used to handle the case when the promise is rejected.

As a result, a Promise is an object that represents the eventual completion (or failure) of an asynchronous operation and its resulting value. Promises provide a way to handle asynchronous operations more efficiently than traditional callback-based approaches.
100daysofcode lebanon-mug

4 Likes