DEV Community

Tasnim Reza
Tasnim Reza

Posted on

3 most powerful JavaScript Promise methods

A Promise is an Object that is used to return a deferred computation. Mostly the deferred computation is asynchronous operation. The function that return a promise, we can attach success and failure callback. For example

fetch('url')
.then(successCallback,failureCallback)
.then(...)
.catch(...)
.finally(...)

In this article, we'll learn 3 most used promise methods.

1. Promise.all

The Promise.all ( iterable ) method returns a new promise object, that fulfils when all the promises passed or any first one is rejected. This method is useful when we need to handle multiple promises.

Imagine a scenario, where we want to make black coffee. We need coffee beans, coffee mate and fresh water. We send 3 request to collect these ingredients. We can make request one after another then it'll take longer time. The efficient way will be if we can make the requests parallel and a way to know when all the requests are finished. Here comes Promise.all

let collectBeans = fetch('bring me Kopi Luwak');
let collectMates = fetch('French Vanilla');
let collectWater = fetch('fresh tubewell water');

Promise.all([
  collectBeans,
  collectMates,
  collectWater])
  .then(ingredients => console.log('make coffee'),
    ohNoo => console.log('Iยดm sorry'));

Promise.all will make sure that all the asynchronous jobs are resolved. If any of them is failed the whole process will be failed. For example if collectBeans failed then Promise.all doesn't care about other two requests. This is the downside of Promise.all

const promise1 = Promise.reject('rejected');
const promise2 = 42;
const promise3 = new Promise((resolve, reject) => {
    setTimeout(resolve, 100, 'foo');
});

Promise.all([promise1, promise2, promise3])
    .then(
        values => console.log(values),
        reason => console.log(reason) // rejected
    );

In this example promise1 is rejected so entire chain is failed. Promise.all is useful when we need to wait for multiple works but the works are not depended to each other.

2. Promise.allSettled

The Promise.allSettled( iterable ) also takes an array of asynchronous job and return a promise object. The promise will be resolved regardless of any rejection. This is the only difference with Promise.all. Promise.all fails if any one is failed.

const promise1 = Promise.resolve(3);
const promise2 = new Promise((resolve, reject) => setTimeout(reject, 100, 'foo'));

Promise.allSettled([promise1, promise2]).
    then(results => console.log(result));

/*
[
    {
        status: "fulfilled",
        value: 3
    },{
        status: "rejected",
        reason: 'foo'
    }
]
*/

In this example, we see promise2 is rejected but the returned promise is resolved with status.

This method is useful, when we need to wait for multiple parallel asynchronous job and they all need to be satisfied (resolve/rejected). This method is useful for REST Api health check.

3. Promise.race

The Promise.race (iterable) is also takes an array of asynchronous job and return a promise object. The promise will be resolved as soon as first resolve of reject happens. When any of the passed promise is resolve or reject, we get the output immediately.

const promise1 = new Promise((resolve, reject) => {
    setTimeout(resolve, 500, 'one');
});

const promise2 = new Promise((resolve, reject) => {
    setTimeout(resolve, 100, 'two');
});

Promise.race([promise1, promise2]).then(value => {
    console.log(value); //two
});
// Output is:
// "two"
// because promise2 is faster

If any of them is reject the output will be the same

const promise1 = new Promise((resolve, reject) => {
    setTimeout(resolve, 500, 'one');
});

const promise2 = new Promise((resolve, reject) => {
    setTimeout(reject, 100, 'two');
});

Promise.race([promise1, promise2]).then(value => {
    console.log(value); // this is never called
}, reason => console.log(reason)); // two

// Output is:
// "two"
// because promise2 is faster

This method is useful, when we need to wait for multiple asynchronous job but we are happy as soon as any of them resolve of reject. For lottery house or broker shop we can use this method.

Summery

Thanks for reading and I hope you learn something from this article. If you have any question please let me know in the comments.

Top comments (3)

Collapse
 
cpandya231 profile image
Chintan Pandya • Edited

My version for handling failure and not skipping all other promises if one is rejected.

dev-to-uploads.s3.amazonaws.com/i/...

Collapse
 
tasnimreza profile image
Tasnim Reza

Amazing, you played well :) yeah it is possible if you add a catch block for each promise.
By the way, you can add code in a comment instead of an image.

Collapse
 
cpandya231 profile image
Chintan Pandya

I thought image would be an alternative, you know would look cool. But dev.to is not showing image same as twitter ๐Ÿ™„