All in one! JavaScript promises…
Tags: javascript, webdev, programming, tutorial
Published: 2022-04-14 08:44:29

Okay! So before starting we’ll make a promise to each other 😅
My Promise: I’ll try to explain Javascript Promises, in the best way possible! 
Your Promise: Read the complete blog! 😃

For now, both of our promises are in a pending state, let’s try to get them fulfilled 🙈

Okay, We’ll start with a small introduction of asynchronous JS... 
A promise is a method that eventually produces value. It can be considered as the asynchronous counterpart of a getter function. Its essence can be explained as:

    promise.then(function(value) {
      // Do something with the 'value'
    });

We know that Javascript is single-threaded & Only one thing can happen at a time, on a single main thread, and everything else is blocked until an operation is complete. So, Suppose if you want to fetch data from the network or database, the main thread will get blocked and how much time it will take to complete we don’t know.
Hence, to solve this problem we have two main types of asynchronous code style:

1. Old-style callbacks

2. Newer promise-style code

We’ll explore each one of it!

    let promise = new Promise(function(resolve, reject){
       // executor (the producing code, "singer") 
    });

The function passed to the new Promise is called the executor. When a new Promise is created, the executor runs automatically. It contains the producing code which should eventually produce the result.

Its arguments resolve and reject are callbacks provided by JavaScript itself. Our code is only inside the executor. When the executor obtains the result, be it soon or late, doesn’t matter, it should call one of these callbacks:

* **resolve(value)** — if the job is finished successfully, with result value.

* **reject(error)** — if an error has occurred, an error is the error object.

## **Promise Chaining**

If we want to execute two or more asynchronous operations back to back, where each requires a previous operation result then chaining comes in!

    chooseProduct()
    .then(up => selectProduct(up))
    .then(cart=> addToCart(cart))
    .then(buy=> buyProduct(buy))
    .catch(failureCallback);

To avoid promise chaining and to write clean code, we have async & await. **Async Await** acts as syntactic sugar on top of promises, making asynchronous code easier to write and read!

    const readData = async() => {
     try{
         const response = await fetch(URL);
         console.log(response);
      }
     catch(err){
        console.log(err);
      }
    }

**There are some static methods of promises in javascript**..

* [Promise.all(iterable)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all)

* [Promise.race(iterable)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/race)

* [Promise.reject(reason)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/reject)

* [Promise.resolve(value)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/resolve)
>  Promise.all()

Promise.all() method takes an iterable of promises as an input and returns a single Promise that resolves to an array of the results of the input promises. It rejects immediately upon any of the input promises rejects.

    p1 = Promise.resolve(50);
    p2 = 200
    p3 = new Promise(function(resolve, reject) {
       setTimeout(resolve, 100, 'geek');
    });
     
    Promise.all([p1, p2, p3]).then(function(values) {
        document.write(values);
    });
>  Promise.race()

The Promise.race() static method accepts a list of promises as an iterable object and returns a new promise that fulfills or rejects as soon as there is one promise that fulfills or rejects, with the value or reason from that promise.

    const p1 = new Promise((resolve, reject) => {
        setTimeout(() => {
            console.log('The first promise has resolved');
            resolve(10);
        }, 1 * 1000);

    });

    const p2 = new Promise((resolve, reject) => {
        setTimeout(() => {
            console.log('The second promise has resolved');
            resolve(20);
        }, 2 * 1000);
    });

    Promise.race([p1, p2])
        .then(value => console.log(`Resolved: ${value}`))
        .catch(reason => console.log(`Rejected: ${reason}`));

    //OUTPUT
    The first promise has resolved 
    Resolved: 10 
    The second promise has resolved

The following example creates two promises. The first promise resolves in 1 second while the second one rejects in 2 seconds. Because the first promise is faster than the second one, the returned promise resolves to the value from the first promise.

**There are some instance Methods of Promise in javascript**..

* [Promise.prototype.then()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then)

* [Promise.prototype.catch()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch)

* [Promise.prototype.finally()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/finally)

![congratulations!!](https://cdn-images-1.medium.com/max/2000/1*LffEwIQcw26faI178F4QtQ.gif)

Finally, we reached our destination. Since you are here, you fulfilled your promise and I hope I was able to keep mine too.

Hope you enjoyed and learned something new! Bye 👋

- Bhavy Kapadia(Programmer Analyst) at [DhiWise](https://www.dhiwise.com/?utm_campaign=externalSEO&utm_source=dev.to)