IggY
IggY

Reputation: 3125

AngularJS : Synchronize multiple independent promises

i'm working on an AngularJS app where Factories (that query the DB) returns promises.

The call to those Factories are encapsulated in functions such as :

function getUsers(id) { 
    MyUserFactory.getUsers(id).then(function(data) { 
        $scope.mydata = data;
        ...lot of code...
    })
}

function updateAcordingToUserAndWeatherOfTheDay(day) {
    MyWeatherFactory.getWeather(day).then(function(data) {
        if ($scope.mydata.likesRain) {
             ...
        }
   })
}

then I have a :

getUser(42); updateAcordingToUserAndWeatherOfTheDay(monday);

Obviously, this works one out of two time, if the async query done by getUser() didn't had time to complete I get an error in updateAcordingToUserAndWeatherOfTheDay() on the $scope.mydata.likesRain

I know I could chain the .then() to force one query to wait for the other but this refactoring would take a lot of time I don't have right now.

Is there another way I can wait for a promise to be completed ? At least to temporary fix the bug before a refactoring. Now the solution we have is a 3 second timer...

Upvotes: 2

Views: 1384

Answers (2)

Adam Jenkins
Adam Jenkins

Reputation: 55772

Refactoring this is very simple, just have the method return the promise.

function getUsers(id) { 
    return MyUserFactory.getUsers(id).then(function(data) { 
        $scope.mydata = data;
        ...lot of code...
    })
}

function updateAcordingToUserAndWeatherOfTheDay(day) {
    return MyWeatherFactory.getWeather(day).then(function(data) {
        if ($scope.mydata.likesRain) {
             ...
        }
   })
}

getUsers(42).then(function() { updateAcordingToUserAndWeatherOfTheDay(day); });

This doesn't have to change any existing code (because returning the promise doesn't break any existing infrastructure), other than the code that you need to modify.

This is the fastest way to refactor to make it work.

Upvotes: 2

sp00m
sp00m

Reputation: 48837

.then() is probably the right way to go. Other solution using callbacks:

function getUsers(id, callback) { 
    MyUserFactory.getUsers(id).then(function(data) { 
        $scope.mydata = data;
        ...lot of code...
        if (typeof callback === "function") {
            callback();
        }
    })
}

getUser(42, function() {
    updateAcordingToUserAndWeatherOfTheDay(monday);
}); 

Upvotes: 1

Related Questions