DEV Community

Cover image for JavaScript Promises Explained: A Startup Analogy for Beginners
Kunal
Kunal

Posted on

JavaScript Promises Explained: A Startup Analogy for Beginners

In this blog we will discuss about Promises and all the methods used in it , with a startup analogy that will make it much more easier to understand.

Topics to Cover

  • What is a Promise
  • Why We Need Promises
  • States of a Promise
  • Creating a Promise
  • Handling a Promise
  • Promise Methods
  • Conclusion

Promise

A promise is an asynchronous operation in JavaScript that represent whether the operation is successful or not .

Its like , building a startup feature and you start the work now but the result ( success or failure ) will come later.

Asynchronous operation :- It is a task that runs in the background and allows other code to execute without waiting it to finish .

Why We Need Promises ?

  1. To handle asynchronous tasks properly
  2. To manage success or failure clearly
  3. To write cleaner and more readable code
  4. To make code more structured
  5. To work efficient with APIs ( Application Protocol Interface ) and background task

States of a Promise

There are three states in Promise.

state

  • Pending :- It is a default state in Promise . It is like the task has started but its still in progress you don't know the result yet.

  • Resolve :- It is the state when the Promise completes successfully and returns a result.

  • Reject :- It is the state when the Promise fails and returns an error , like when something doesn't go as planned.


Creating and Handling a Promise

In a startup journey , there are three main steps and promises works the same way.

Creating a promise

This is like starting a new project . You decide to build something but you don't know the outcome yet.

In JavaScript , promise are create by using

const promise = new Promise((resolve , reject) => {...})
Enter fullscreen mode Exit fullscreen mode

In this you also don't know the outcome yet it can be resolved or rejected.

Handling a Promise

After launching the project you will wait for the result.
If it succeed you celebrate and fails you fix it .

In JavaScript , Promise are always handled by .then() , .catch() , .finally().

const promise = new Promise((resolve, reject) => {
  resolve("Promise Resolved");
  reject("Promise Rejected");
});

promise
  .then((data) => {
    console.log(data);
  })
  .catch((error) => {
    console.log(error);
  })
  .finally(() => {
    console.log("code ends");
  });

Enter fullscreen mode Exit fullscreen mode

If the promise is resolved then it goes to .then() section
If promise got rejected then it goes to .catch() section
.finally() will always executed irrespective of the resolve or reject

So if we have to deal with multiple promises we can do this but it is not verbose. So there are several methods to deal with multiple promises.


Promises Methods

These are the methods that directly applied on the Promise class. Not on an individual promise object like .then() , .catch() , .finally()

const promise = Promise.methodName()
Enter fullscreen mode Exit fullscreen mode

These are the helper methods provided by JavaScript so we dont use new keyword here.

Lets see one by one :

1. Promise.resolve()

  • It returns a promise that is already successfully resolved.
  • It is like a client that trust you who instantly approves your proposal without delay.

resolve

2. Promise.reject()

  • It return a promise that is already rejected with an error
  • Its like a manager who instantly rejects your leave with a silly excuse

reject

3. Promise.any()

  • This method takes an array of promises as input and returns a single promise.
  • It waits for the first promise that resolves successfully. If all promises fail then it rejects.
  • It is like pitching your idea to multiple investors you just need one yes to move forward. If everyone says no, then it fails.

any

Promise.any() only cares about the first promise that resolve. promise2 and promise3 still running in the background but their result will be ignored.

4. Promise.all()

  • It also takes an array of promises and waits for all promises to succeed. If one fails everything fails.
  • It is like all departments (design, development, marketing) must finish work before launch. If one fails, launch fails.

all

5. Promise.allSettled()

  • It is similar to Promise.all but it waits for all promises to settle either resolve or reject
  • It returns an array of object with the status of each promise.
  • It is like you review every departments result some succeeded, some failed but you still get the full report.

allSettled

6. Promise.race()

  • This method takes an array of promises as an input and returns a single promise.
  • It will return the promise as soon as any promise is either resolve or rejcted.
  • Two investors respond whoever replies first decides your direction.

race


Conclusion

Javascript promises help us handle tasks that dont finish instantly.

From creating a promise to handle it with .then() , .catch() , .finally() and using methods like all() , any() . that gives a structure to the async code.

Instead of writing poor code promises helps us to make our code cleaner and more readable and easier to manage.


Thanks for reading ! if enjoyed this blog , you can read more on this πŸ‘‡

Top comments (0)