Search code examples
javascriptjquerypromiserevealing-module-pattern

Javascript promise not delaying function execution


I'm using ES6 javascript promises in Chrome and am having trouble understanding why the promise executed within the function _getStatus() is not returning the result argument in the success handler which would result in the alert box containing "done". Instead, I get an alert box that says "undefined".

myNameSpace = function(){    
    var obj = {
        groupA: {
            status: "inactive"
        },
        groupB: {
            status: "active"
        }
    };

    function _getStatus(group){
        _finishTask().then(function(result){
            return result; // doesn't return anything
        });
    }

    function _finishTask(){
        var promise = new Promise(function(resolve, reject){            
            // do some task before resolving
            resolve("done");
        });
        return promise;
    };

    return{
        getStatus:_getStatus
    }
}();

$(function(){
    alert(myNameSpace.getStatus("groupA")); // why is this "undefined" instead of "done"?
});

Solution

  • Because this is not how Promises work. You need to make sure both _getStatus and _finishTask return Promise objects. Then you will be able to use those promises API methods to execute subsequent code what promise is resolved.

    So your code should look something like this:

    myNameSpace = function() {
        var obj = {
            groupA: {
                status: "inactive"
            },
            groupB: {
                status: "active"
            }
        };
    
        function _getStatus(group) {
            return _finishTask().then(function(result) {
                return result + " and tested";
            });
        }
    
        function _finishTask() {
            return new Promise(function(resolve, reject) {
                // do some task before resolving
                resolve("done");
            });
        };
    
        return {
            getStatus: _getStatus
        }
    }();
    
    myNameSpace.getStatus("groupA").then(alert);
    

    Finally, regarding this construction:

    return _finishTask().then(function(result) {
        return result;
    });
    

    _finishTask returns a Promise object, when this promise is resolved you get into then callback. Whatever value you return from this callback becomes a new resolution value for the subsequent success callbacks down the resolution chain.

    Demo: http://plnkr.co/edit/K1SWKuTYA3e46RxdzkCe?p=preview