Skip to content Skip to sidebar Skip to footer

How To Handle Recursive Asynchronous Db Calls That Modify The Same Variable

Building a JS app with Ionic framework and Firebase. I want the app to suggest to each user a list of users to discuss with based on countries they visited. Come firsts in the sugg

Solution 1:

Use the $q.all method on a hash of promises:

functiongetRegistrationsFromCountryList(countryList){
    var promiseHash = {};
    countryList.foreach(function (country) {
        promiseHash[country] = firebase.database().ref('/country_user/' + country).once('value');

    });
    return$q.all(promiseHash);
};

The above example returns a promise that resolves to a hash of registrations keyed to each country in the countryList.

To use with the countryListPromise, simply chain the promises:

var promise = getUserCountryListPromise(uid);

var registrationsHashPromise = promise.then(function(countryList) {
    //return promise to chainreturngetRegistrationsFromCountryList(countryList);
});

registrationsHashPromise.then(function(regsHash) {
    angular.forEach(regsHash, function(regs, country) {
       console.log(country + ": " + regs); 
       //update matches list
    });
});

Because calling the .then method of a promise returns a new derived promise, it is easily possible to create a chain of promises. It is possible to create chains of any length and since a promise can be resolved with another promise (which will defer its resolution further), it is possible to pause/defer resolution of the promises at any point in the chain. This makes it possible to implement powerful APIs.

--AngularJS $q Service API Reference -- Chaining Promises.

Post a Comment for "How To Handle Recursive Asynchronous Db Calls That Modify The Same Variable"