Learn JavaScript Promise method in easiest way

Learn JavaScript Promise method in easiest way

The Promise is an object that may produce a value, sometime in the future, on the completion of an asynchronous operation. The produced value can be either a successful result or an error .

Real World example of JavaScript Promise

A car factory provides promise to the buyers. It says if the buyers provide the money then they will get a new car in the future.

So here are 2 cases – either the buyers get car (successful result), or if some problem occurs in the factory like workers strike, fire, floods, etc then the money is refunded to the buyers (error).

Syntax of JavaScript Promise

The syntax is given below:

myPromise = new Promise(function (resolve, reject) {
    // some code
});

myPromise.then(
    result => { // executes when promise is resolved },
    error => { // executes when promise is rejected }
);
The function passed to new Promise is called the executor. When the promise is created, this executor function runs automatically. The executor will produce some result (successful result or error) in the future.
resolve & reject
The resolve and reject are the callback methods which the executor calls when the job is finished.
  • Resolve = called with the job is finished successfully i.e. promise is resolved
  • Reject = called when the job results in an error i.e. promise is rejected
then
Consuming functions are registered using the .then method. The first argument (result => {}) is a function that executes when promise is resolved (successful result) while the second argument (error => {}) is a function that executes when promise is rejected (error).

JavaScript Promise works Asynchronously

The JavaScript will not wait for the promise to finish instead will continue to the next lines of code. When the promise finishes then the consuming functions will automatically be called.

In the below code the promise takes 2 seconds time so JavaScript just continue executing the next lines of code and then after 2 seconds the resolve callback function is called.

Therefore the second console.log will be executed first then afterwards the ‘console.log’ inside the resolve callback function is executed.

myPromise = new Promise(function (resolve, reject) {
    setTimeout(resolve, 2000, "completed");
});

myPromise.then(
    result => { console.log(result) },
    error => { alert(error) }
);

console.log("Doing other work");
The output of the code will be:
Doing other work
completed
Similarly, I also created some great features with APIs and you should check them to:

1. Implementing TheMovieDB (TMDB) API with jQuery AJAX
2. JQuery AJAX Method to Call an API
3. Implementing Google Contacts API

Simple Example of JavaScript Promise

Inside the executor I am calling the resolve callback function after 2 seconds time. I also passed ‘completed’ to the resolve callback. When you run the below code you will see alert box showing ‘completed’.
myPromise = new Promise(function (resolve, reject) {
    setTimeout(resolve, 2000, "completed");
});

myPromise.then(
    result => { alert(result) },
    error => { alert(error) }
);
Similarly the below code the executor throws an error resulting in promise being rejected. Therefore the reject callback function is executed.
myPromise = new Promise(function (resolve, reject) {
    throw new Error('Something failed');
});

myPromise.then(
    result => { alert(result) },
    error => { alert(error) }
);
You can also call the reject callback like reject(“Something failed”);.

Catching JavaScript Promise Errors

If there happens to be some error then promise gets rejected. You can capture these errors using .catch() method. This method is used after the .then() method.

In the below code I am catching error using the .catch() method. Notice that I haven’t added the error callback function.

myPromise = new Promise(function (resolve, reject) {
    throw new Error('Something failed');
});

myPromise.then(
    result => { alert(result) }
).catch(result => { alert(result) } );
You do not need .catch() method if you are using error callback method.

Promise Chaining

If there is a need to execute two or more asynchronous operations back to back in such a way that each subsequent operation starts when the previous operation succeeds, also the subsequent operation takes the result of the previous operation. This is accomplished by creating Promise Chaining.

Consider the below code where the result is passed through the chains of ‘.then’ method.

myPromise = new Promise(function (resolve, reject) {
    setTimeout(() => resolve(1), 1000); // (*)
});

myPromise.then( // (**)
    result => {
        console.log(result); // 1
        return result * 2;
    })
    .then(
    result => { // (***)
        console.log(result); // 2
        return result * 2;
    })
    .then(
    result => { // (****)
        console.log(result); // 4
    });

The output you will get is:

1
2
4

The flow is:

  • a. First initial promise is resolved in 1 second (*).
  • b. Then the .then() method (**) is called which prints 1 to the console.
  • c. The value that it returns is passed to the next .then() (***) and it prints 2 to the console.
  • d. The value of 4 is passed the final .then()(****) and 4 is printed on the console.
In the above code the a value returned by a .then() method is immediately passed to the next .then(). I can change it to pass a new promise in the .then() method. This is shown in the below code:
myPromise = new Promise(function (resolve, reject) {
    setTimeout(() => resolve(1), 1000); // (*)
});

myPromise.then(
    result => {
        console.log(result); // 1
        return new Promise((resolve, reject) => {
            setTimeout(() => resolve(result * 2), 1000);
        });
    })
    .then(
    result => {
        console.log(result); // 2
        return new Promise((resolve, reject) => {
            setTimeout(() => resolve(result * 2), 1000);
        });
    })
    .then(
    result => {
        console.log(result); // 4
    });
The output is same like before except that there is a delay of 1 second every time:
1
2
4

Calling an API with JavaScript Promise

Here I will call an API that returns random jokes with JavaScript Promise.

The API URL is: https://api.icndb.com/jokes/random.

The JSON returned by it is:

{ "type": "success", "value": { "id": 215, "joke": "Chuck Norris just says no to drugs. If he said yes, it would collapse Colombia's infrastructure.", "categories": [] } }
Run the below code that fetches random joke from the API:
myPromise = new Promise((resolve, reject) => {
    const request = new XMLHttpRequest();
    request.open('GET', 'https://api.icndb.com/jokes/random');

    request.onload = () => {
        if (request.status === 200) {
            resolve(request.response); // we got data here, so resolve the Promise
        } else {
            reject(request.statusText); // status is not 200 OK, so reject
        }
    };

    request.onerror = () => {
        reject(Error('Error fetching data.')); // error occurred, reject the  Promise
    };

    request.send(); // send the request
});

myPromise.then(
    result => { console.log(JSON.parse(result).value.joke); },
    error => { alert(error); }
);

Explanation: Inside the Promise I am making an XMLHttpRequest object to make an AJAX request. The reason for making AJAX request inside the Promise is because the API will send the response in a few milliseconds time. So promise is a best solution.

When the promise gets the response I am printing the joke in the console.

Download source codes:

DOWNLOAD

SHARE THIS ARTICLE

  • linkedin
  • reddit
yogihosting

ABOUT THE AUTHOR

I hope you enjoyed reading this tutorial. If it helped you then consider buying a cup of coffee for me. This will help me in writing more such good tutorials for the readers. Thank you. Buy Me A Coffee donate

Leave a Reply

Your email address will not be published. Required fields are marked *