Search code examples
javascriptpromiseqchain

Wait execution of a new inner promise


I'm new to this promises world and I got quite a situation I don't know what to do.

I have a new promise been called by the result of the first promise.

Here is the situation:

    function asyncCall(object){
           return firstObject.loadSomething(object).then(function(result) {
               result.innerAsyncCall().then(function() {
                    finalCode();
               });
           });
    }

I loop over asyncCall and build a $q.all().then() to wait for the promises to resolve.
However, since the inner promise is not chained it runs independently.
Sample Code:

var promises = [];
array.forEach(function(object){
     promises.push(asyncCall(object));
});

$q.all(promises).then(function(){
     console.log('Done!!');
});

The question is. What can I do to wait the full execution of the inner promise?


Solution

  • If you resolve a promise with a promise, it will "recursively" adopt its state and wait for the innermost one. In the case of a .then() call, the new promise is resolved with the return value of the callback - so you just have to add a return to your code and it'll work:

    function asyncCall(object) {
        return firstObject.loadSomething(object).then(function(result) {
            return result.innerAsyncCall().then(function() {
    //      ^^^^^^
                finalCode();
            });
        });
    }
    

    Notice that you can also flatten this into a chain:

    function asyncCall(object) {
        return firstObject.loadSomething(object).then(function(result) {
            return result.innerAsyncCall();
        }).then(finalCode);
    }