Martijn Martijn - 6 days ago 4
AngularJS Question

How to handle nested promises?

I'm fairly new to the promises concept, at least at creating them. I've read documentation how they work and I get how a promise works. I also understand how you can trigger some callback when all promises are done, I just don't get it how to implement it in my code.

My code simplefied:

function start_it_all(){
return $cordovaSQLite.execute(db, "SELECT foo FROM bar").then(function(result) {
return anotherFunction();
});
}
function anotherFunction(){
return $http.get('foo.php').then(function(){
// Here I get some data
});
}


Both the
$cordovaSQLite
and the
$http
are async. I need to be able to do this:

start_it_all().then(function(){
// Hide Loading animation (no further return data needed).
});


I understand that the
.then()
are the promise handlers, but as I currently have it, it returns just the promise of the query, I want the
$http
to give the promise. At this point I get
TypeError: Cannot read property 'then' of undefined
on the
start_it_all().then()


Can anyone explain how to do that?

Answer

You don't have to nest those promises, you can do the following:

function start_it_all(){
    return $cordovaSQLite.execute(db, "SELECT foo FROM bar")
    .then(function(result) {
        return $http.get('foo.php');
    })
    .then(function(){
            // Here I get some data
    });
}

Based on the comments in the original question, the .then method of $cordovaSQLite.execute seems not to be Promise/A+ compliant

to fix this, wrap $cordovaSQLite.execute(...) in Promise.resolve

function start_it_all(){
    return Promise.resolve($cordovaSQLite.execute(db, "SELECT foo FROM bar"))
    .then(function(result) {
        return $http.get('foo.php');
    })
    .then(function(){
            // Here I get some data
    });
}

and, now, based on comment and edited question

function start_it_all(){
    return Promise.resolve($cordovaSQLite.execute(db, "SELECT foo FROM bar"))
    .then(anotherFunction)
    .then(function(){
            // Here I get some data
    });
}

As pointed out by @LenilsondeCastro - in angular you can use $q.when above where I've used Promise.resolve