02 March 2017 - Upkar Lidder Open Issue

Others have explained promises and how to use them way better than I ever will. So here are some of the cool articles I like:


I wrote two simple files in Nodejs that demostrate how to create and use promises. The fake api simply returns promise back along with logic on what to do when this promise is resolved or rejected. The client calls this API and uses then to handle successful case or catch to handle failure.

Fake API

API that returns a promise and fakes asynchronous call using setTimeout function.

        "use strict";
        var log4js = require('log4js');
        var logger = log4js.getLogger('fakeapi');
    function fakePromise() {
        var greeting = null;
        var isSuccess = true;

        logger.debug('api called');

        var p = new Promise(function(resolve, reject) {
            setTimeout(function() {
                logger.debug('api finished');
                if (isSuccess) {
                    greeting = 'hello world';
                } else {
                    reject('Something terrible happened !');
            }, 3000);
        return p;

    module.exports = fakePromise;


Code that uses this fake API and uses the returned promise.

        "use strict";
        var api = require('./fakeapi');
        var log4js = require('log4js');
        var logger = log4js.getLogger('app');
    logger.debug('start program');
    logger.debug('call api');
    api().then(function(data) {
        logger.debug('promise resolved');
    }).catch(function(err) {

    var d = new Date();
    logger.debug("end program");


        Debugger listening on
        [2017-03-02 10:40:26.901] [DEBUG] app - start program
        [2017-03-02 10:40:26.903] [DEBUG] app - call api
        [2017-03-02 10:40:26.903] [DEBUG] fakeapi - api called
        [2017-03-02 10:40:26.904] [DEBUG] app - end program
        [2017-03-02 10:40:29.908] [DEBUG] fakeapi - api finished
        [2017-03-02 10:40:29.909] [DEBUG] app - promise resolved

Open Issue

Back home