AngularJS Sequentially Chain Promises in forEach Loops

…衆ロ難τιáo~ 提交于 2019-12-02 08:08:05

The calls to the factory asynchronous API are being made in parallel. They need to chained sequentially:

vm.reviewWeek = function () {

    //Array to be updated over each iteration and used in factory call
    var trackMenuIds = [];

    //INITIAL empty promise
    var promise = $q.when();

    angular.forEach(vm.planWeek.dinner, function (day) {

        //Adds two more items to day(current row) to pass to factory
        day.menuType = 'dinner';
        day.weekIds = trackMenuIds;

        //Factory call - each time this runs, the 'trackMenuIds' array should have 
        //one more item added from the previous run

        //CHAIN sequentially
        promise = promise.then(function () {
            //RETURN API promise to chain
            return menuFactory.matchMenuCriteria(day);
        }).then(function (response) {
            var randomItem = response.data[0];
            day.menuItem = {'_id': randomItem._id, 'name': randomItem.name};

            //adds the current id to the array to be used for the next run
            trackMenuIds.push(randomItem._id);
        });
    });

    return promise;
};

The above example creates an initial empty promise. The foreach loop then chains a call to the asynchronous API on each iteration.

You can use $q.all to handle multiple asynchronous call. Once all promise done execute, loop through raw Http promise and then push the data to the new array

vm.reviewWeek = function () {

    //Array to be updated over each iteration and used in factory call
    var trackMenuIds = [];

    var dinnersPromise = [];

    vm.planWeek.dinner.forEach(function (day, ind) {
        //Adds two more items to day(current row) to pass to factory
        day.menuType = 'dinner';
        day.weekIds = trackMenuIds;
        dinnersPromise.push(menuFactory.matchMenuCriteria(day));
    });

    $q.all(dinnersPromise).then(function (arr) {
        angular.forEach(arr, function (response) {
            var randomItem = response.data[0];
            day.menuItem = {'_id': randomItem._id, 'name': randomItem.name};

            //adds the current id to the array to be used for the next run
            trackMenuIds.push(randomItem._id);
         });
    });
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!