Search This Blog

2018/09/07

Javascript Promise & Async/await

What is promise ?
    Promise is an object that represent result of  asynchronous operation in future.Promise can be in one of following state

        1) pending - The initial state of a promise.
        2) resolved - The state of a promise representing a successful operation.
        3) rejected - The state of a promise representing a failed operation.

    Once a promise is resolved or rejected it remain so it can't change it state further.In sense it is immutable.

Initial Javascript do not have native promises library though there were third party implementation like Deferred,Q,Asyc.js or bluebird.
ES6 brought a Promises natively to javascript.

Only the function responsible for creating the promise will have knowledge of the promise status, or access to resolve or reject.
The ES6 promise constructor takes a function. That function takes two parameters, resolve(), and reject().
You can resolve() or reject() with values, which will be passed to the callback functions attached with .then().
e.g.
     assume we want to get IP address of client through REST API.'request-promise' is promisified version of 'request' library.
promise provide alternative to callback.

    var Request = require("request");
    var RequestPromise = require('request-promise');

    var getPublicIp = function () {
        return new Promise(function (resolve, reject) {
        RequestPromise('http://httpbin.org/ip')
            .then(function (htmlString) {
                resolve(JSON.parse(htmlString))
            })
            .catch(function (err) {
                reject(err)
            });
        }
        );
    }

we can call this function as

    getPublicIp()
        .then(function (fulfilled) {
        console.log('Public Ip Address:' + fulfilled.origin)
        })
        .catch(function (error) {
        console.log("Error:" + error);
        })

or using async/await as

    async function getPublicIpAsyc() {
        try {
        var result = await getPublicIp();
        console.log("Async/Await:" + JSON.stringify(result))
        } catch (err) {
        console.log("Async/Await:" + err)
        }

    }

    getPublicIpAsyc();

Here await can be used only inside function which is defined as async.Async/await is new feature that await ask calling function to wait till get response of statement marked with await.
async/await let us to handle exception in single try catch unlike promise where we have to chain catch block after then block.

No comments:

Post a Comment