Reading list Switch to dark mode

    Promises in JavaScript

    Updated 12 April 2024

    Introduction:

    JavaScript is single-threaded, which means two bits of the script cannot run at the same time. They run one after another. A Promise is an object that allows you to associate handlers with an asynchronous action’s eventual success value or failure reason.

    Before proceeding, we should know about what is the difference between synchronous and asynchronous action. Synchronous means only one line of code will be executed at the same time but in the case of Asynchronous action, multiple lines of code will be executed simultaneously rather than one after another.

    Promises in JavaScript exist in one of the following 3 states:

    • Pending: This is the initial state, which means that the operation was neither fulfilled nor rejected.
    • Fulfilled: It means the operation was completed successfully.
    • Rejected: It means the operation failed.

    Syntax:

    let promise = new Promise(function (resolve, reject) {
        // executor
    });

    In the above code, the executor is a function passed to new Promise. When new Promise is created, the executor runs automatically.

    Resolve and reject are two callbacks provided by JavaScript itself. They are called like this:

    Searching for an experienced
    WordPress Company ?
    Find out More

    resolve(value): If the job is finished successfully.
    reject(error): If the job fails.

    The promise object can be created by the new Promise() constructor. It has the following two properties:

    • State: Initially it is pending, then changes to either “fulfilled” when resolve is called or “rejected” when reject is called.
    • Result: Initially undefined, the changes to value if resolved or error when rejected.

    then, catch, and finally Methods

    then: It is used to display the resolved data after the fulfillment of promises.

    The syntax of .then() is:

    promise.then( function(result){/*handle*/},
    function(error){/*handle*/}
    );

    If we are interested only in successful completions, we can provide only one function argument to
    .then();

    let promise = new Promise( resolve => {
    SetTimeout( () => resolve(“done”), 1000);
    });
    promise.then(alert);

    If we are interested only in errors, we can use null as the first argument: then(null, f)

    Or, we can use .catch() method:

    promise.catch(alert);

    catch: It is used when a promise is rejected. You can handle errors using .catch() function.

    finally: It is used to perform general cleanups. When we want to do something after either a promise is resolved or rejected, we can use the .finally() method:

    promise.finally( () => {
       //do something..
    });

    Promise Chaining:

    We can chain promises and make then pass the resolved values to one another like this:

    p.then( function( result ) => {
    alert(result); return 2;
    }).then… // Here p is a promise.

    The idea is to pass the result through the chain of .then handlers.

    Here is the flow of execution:

    1. The initial promise resolves in 1 second (Assumption).
    2. The next .then() handler is then called, which returns a new promise (resolved with 2 values).
    3. The next .then() gets the result of the previous one and this keeps on going.

    Every call to .then( ) returns a new promise whose value is passed to the next one and so on. We can even create custom promises inside .then()

    We can attach multiple handlers to one promise. They don’t pass the result to each other; instead they process it independently.
    let p is a promise.
    p.then(handler1)
    p.then(handler2)
    p.then(handler3)


    All above handlers run independently.

    Promise API:

    There are 6 static methods of Promise class:

    1. Promise.all(promises): Waits for all promises to resolve and returns the array of their results. If anyone fails, it becomes an error & all other results are ignored.
    2. Promise.allSettled(promises): Waits for all the promises to settle and returns their results as an
      array of objects with status and value.
    3. Promise.race(promises): Waits for a first promise to settle and its result/error becomes the outcome.
    4. Promise.any(promises): Waits for the first promise to be fulfilled (or not rejected), and its result becomes the outcome. Throws an Aggregate Error if all the promises are rejected.
    5. Promise.resolve(value): Makes a resolved promise with the given value.
    6. Promise.reject(error): Makes a rejected promise with the given value.

    If you need custom WordPress Development services then feel free to reach us.

    . . .

    Leave a Comment

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


    Be the first to comment.

    Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home

    Table of Content