September 29, 2018

Javascript Promises with chaining in ES6

 Javascript in version ES6 has introduced Promises. They allow asynchronous tasks to be coordinated. A promise takes two arguments resolve and reject and the asynchronous code calls one of them depending on result. An example would be to fetch a file from network.

The promise can register functions to be called after resolve is called using 'then' method. Similarly, functions to be called after reject are registered using 'catch' method.

'then' method in turn returns a new promise which can be chained.

Following is an annotated example which demonstrates these concepts.


/* Create a new promise with async action inside
    It takes two functions as arguments: resolve, reject */
const myPromise = new Promise( (resolve, reject)=>{
    /* This function represents async work */
    function doWork () {
        // If current time is even then resolve else reject.
        const fulfilled = (((new Date()).getTime()) % 2 == 0);
        (fulfilled)? resolve(fulfilled): reject(fulfilled);
    }
    // Schedule the work after some time.
    setTimeout(doWork, 1000);
    // Return before doWork finishes.
    return;
});

// If resolve is called in doWork function then call following function.
var myPromise2 = myPromise.then( (fulfilled) => {
    console.log("Resolved with " + fulfilled);
    return fulfilled;
});

// If reject is called in doWork function then call following function.
myPromise.catch( (fulfilled)=>{
    console.log("Rejected with " + fulfilled);
    return fulfilled;
});

// Chain this function after "Resolved With " is called.
myPromise2.then( (fulfilled)=>
    console.log('Chained Promise with ' +  fulfilled));



No comments:

Post a Comment