An ultimate guide to JavaScript Promises

An ultimate guide to JavaScript Promises

·

3 min read

Before diving in, you should have a bare understanding of what is asynchronous programming. For more on that, check out this series. Let's look at how to use a promise:

MakeRequest is our function which returns a promise. This promise has some method like .then(a, b) which accepts 2 functions as arguments. The first function is executed on promise success. The second is executed on promise fail.

MakeRequest('https://website.com')
     .then((data) => {
        // this is our first function. Execute when the request is successful (resolves). 
     }, (err) => {
         // this is our second function. Executed if function fails(rejected)
     })

Creating promise

Let's show you how to create the promise which we used above.

function MakeRequeat(location) {
    return new Promise((resolve, reject) => {
        // here you put all asynchronous code. 
        console.log(`input is ${location}`)

        if (typeof location === "string") {
            // call `resolve()` when taks is executed successfully
            resolve('Operation successful!')
        } else {
            reject('Operation failed')
        }
    }); 
}

together

Let's put everything together.

image.png

Instead of resolve/reject, you can put whatever parameter names you want. Those are just the most commonly used. Now you can see above and try to get example fully.

So what's the point?

I hope you understood it all up to know, but you might as - what's the point of all this waiting and receiving resolve/reject? That's it?

const p = new Promise((resolve, reject) => {
    // here you put resources consuming tasks, like requests to servers/datbase/filesystem or doing 100000 operations (which takes time) 
    setTimeout(() => { resolve('foo')}, 3000 ); 
    // when the task finsishes, if it is successful you call resolve. Else (if error) call reject
 }).then((resolve) => {
     // then receives two function. First called on resolve, second on reject. If once function passed as parameter only, it is exec for resolve. 
     console.log(resolve)
 });

In real life

We frequently won't create the promises, rather we would use them from external libraries like axios, which I introduced you to before awhile. Here's a simple example:

axios.get('https://website.com')
    .then(response => {
        console.log(response) 
    }).catch(err => {
        // catch is the same as passing the seocn function argument in .then()
    })

Promised advance concept

Now that you got what are promises, let's dive deeper.

let one = new Promise(() =>{resolve('onee')}); 
let two = new Promise(() =>{resolve('twoo')});

Here we've detected two simple promises which always resolve. What if we want to do something after all of them resolve? Let's see.

Promise.all([one, two]).then((messages) => {
    console.log(messages); 
    // this 'messages' parameter holds an array which containes all of the resolved results. ['onee', 'twoo'] gets logged in
});

Okay, Promise.all().then() is executed when all of the asynchronous stuff inside each, individual promise has finished. What if we want to execute .then after the first promise is finished? Use .race() instead of .all()

Promise.race([one, two]).then((messages) => {
    console.log(messages); 
    // as soon as one of the promises (one, two) is finished, this .then() will be executed. 
});

Now I would stop here. Thanks for Reading.

Did you find this article valuable?

Support Rahul by becoming a sponsor. Any amount is appreciated!