简体   繁体   中英

resolve multiple promises in angularjs

Here is my factory which gets data from an API and stores each data to a SQLLite database.

team.factory('dataSync', function($q,$http,$timeout,$cordovaSQLite ){
    return {
        getData:function(){
            var q = $q.defer();
             $http.get(api+'/sync/').then(function(response){
                q.resolve(response);
            },function(error){
                q.reject();
            })
            return q.promise;

        },

        saveData:function(){
            var q= $q.defer();

            this.getData().then(function(result){
                var data= result.data;
                var sharing = data.sharing;
                var help = data.help;
                var message = data.message;
                var questions = data.question;

                var promises = [];

                angular.forEach(sharing, function(value, index) { 
                        console.log(value);
                    var sharingsql="INSERT INTO sharing (id,content_order,content ,last_modified)VALUES(?,?,?,?)";

                     $cordovaSQLite.execute(db,sharingsql,[value.id,value.content_order,value.content,value.last_modified]).then(function(result){
                        console.log(result.insertId);
                        //q.resolve(true);
                     },function(error){
                        console.log(error.message);
                     })
                });
                angular.forEach(help, function(value, index) { 
                    console.log(value.message);
                    var helpsql="INSERT INTO help (id,message,message_position,last_modified)VALUES(?,?,?,?)";

                     $cordovaSQLite.execute(db,helpsql,[value.id,value.message,value.message_position,value.last_modified]).then(function(result){
                        console.log(result.insertId);
                     },function(error){
                        console.log(error.message);
                     })
                });

                    angular.forEach(message, function(value, index) { 
                    var messagesql="INSERT INTO messages (id,message,message_position,last_modified_date)VALUES(?,?,?,?)";

                     $cordovaSQLite.execute(db,messagesql,[value.id,value.message,value.message_position,value.last_modified]).then(function(result){
                        console.log(result.insertId);
                     },function(error){
                        console.log(error.message);
                     })
                });

                    angular.forEach(questions, function(value, index) { 
                    console.log(value.id+' '+index);
                    var questionsql="INSERT INTO questions (id,question_status,questions,question_order,last_modified)VALUES(?,?,?,?,?)";

                     $cordovaSQLite.execute(db,questionsql,[value.id,value.question_status,value.question,value.question_order,value.last_modified]).then(function(result){
                        console.log(result.insertId);
                     },function(error){
                        console.log(error.message);
                     })
                });


                    $timeout(function(){

                    },2000).then(function(){

                        //q.resolve(true);
                    })


            },function(error){
                q.reject();
            });
            return q.promise;
        }

    }
});

The call to $cordovaSQLite.execute returns a promise.

I want to return true after all the promises are resolved. How can I resolve all the promises that are resolved in each loop?

When I searched about this I found $q.all as an answer. Then I have read some tutorials about this but cannot implement here.

put all promises into an array and then use $q.all(yourArray).

Here is your updated code - You don't need to use $q.defer() since $http already returns a promise - and all your $cordovaSQLite promises will be resolved by themselves

team.factory('dataSync', function($q,$http,$timeout,$cordovaSQLite ){
    return {
        getData:function(){
            return $http.get(api+'/sync/').then(function(response){
                return response;
            },function(error){
                $q.reject();
            })
        },
        saveData:function(){
            return this.getData().then(function(result){
                var data= result.data;
                var sharing = data.sharing;
                var help = data.help;
                var message = data.message;
                var questions = data.question;

                var promises = [];

                angular.forEach(sharing, function(value, index) { 
                        console.log(value);
                    var sharingsql="INSERT INTO sharing (id,content_order,content ,last_modified)VALUES(?,?,?,?)";

                     promises.push($cordovaSQLite.execute(db,sharingsql,[value.id,value.content_order,value.content,value.last_modified]).then(function(result){
                        console.log(result.insertId);
                        //q.resolve(true);
                     },function(error){
                        console.log(error.message);
                     }));
                });
                angular.forEach(help, function(value, index) { 
                    console.log(value.message);
                    var helpsql="INSERT INTO help (id,message,message_position,last_modified)VALUES(?,?,?,?)";

                     promises.push($cordovaSQLite.execute(db,helpsql,[value.id,value.message,value.message_position,value.last_modified]).then(function(result){
                        console.log(result.insertId);
                     },function(error){
                        console.log(error.message);
                     }));
                });

                    angular.forEach(message, function(value, index) { 
                    var messagesql="INSERT INTO messages (id,message,message_position,last_modified_date)VALUES(?,?,?,?)";

                     promises.push($cordovaSQLite.execute(db,messagesql,[value.id,value.message,value.message_position,value.last_modified]).then(function(result){
                        console.log(result.insertId);
                     },function(error){
                        console.log(error.message);
                     }));
                });

                    angular.forEach(questions, function(value, index) { 
                    console.log(value.id+' '+index);
                    var questionsql="INSERT INTO questions (id,question_status,questions,question_order,last_modified)VALUES(?,?,?,?,?)";

                     promises.push($cordovaSQLite.execute(db,questionsql,[value.id,value.question_status,value.question,value.question_order,value.last_modified]).then(function(result){
                        console.log(result.insertId);
                     },function(error){
                        console.log(error.message);
                     }));
                });
                return $q.all(promises);
            },function(error){
                return $q.reject();
            });
        }
    }
});

This way when you call saveData() it will return a promise that will be resolved once all your $cordovaSQLite are resolved, and you can use .then() to do what you want after all that happen.

Note: I think all error handlers can be removed and use only one "catch" function

Yes use $q.all() . Push the promises into the array, but remove the .then() callbacks. Promise.then() returns a promise so if the .then() callbacks are not removed, they would need to be updated to return the arguments (ie result ).

promises.push($cordovaSQLite.execute(db,sharingsql,[value.id,value.content_order,value.content,value.last_modified]))

Then use $q.all(promises) by calling .then() on it, where true can be returned:

$q.all(promises)
  .then(function(responses) {
    //all promises have been resolved
    return true;
  })

See a demonstration in this plunker .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM