0

I hope someone can help me better understand the promises. I'm pretty rookie with them. I'm doing a DB query with promises, when the result is correct get an array of data. Then I need to make a loop iterating this array and perform for each element delete operation and after that delete operation to another operation of sending, when both operations finished, then, repeat the process for each element of the array, but must be completed for each element the finish operation and send operation before starting another array element ... with my code that does not happen, the loop make delete operation for each element without awaiting the delete and send operation return result.... Both operation delete and shipping have the structure

function x (makeQuery){
  .......
  var deferred = Q.defer();
   .....
   function(err, result) {
                    if (err) {
                      deferred.reject(err);
                    } else {
                     deferred.resolve(result);
                    }

                });
  return deferred.promise;
}

And my code is :

 getElementInPostgres(makeQuery)
        .then(function (obj) {
          if (...){
                results= obj['rows']
                index =0
                for (var i = 0; i < results.length; i++) {
                    var notification = {}
                  notification.tag='SubscriptionNode'
                  notification.indexSocket=results[i]['indexsocket']
                  notification.clientID=results[i]['clientid']
                  notification.callbackURL=results[i]['callbackurl']
                  notification.deploymentID=results[i]['deploymentid']
                  notification.clusterID=results[i]['clusterid']
                  notification.date=results[i]['registered']
                  var query = "DELETE FROM.....";
                  var params = [notification.indexSocket];
                  deleteInPostgres(query,params,notification)
                  .then(function (notification) {
                      if(notification.clientID){
                          sendInfoToPython(notification)
                           .then(function (obj) {
                               ..........
                           }).fail(function (err) {
                              ......
                           });
                      }

                  }).fail(function (err) {
                    ......
                   });
                 }
               }
               else{
                .........
               }
              }).fail(function (err) {

                });
AnD
  • 125
  • 1
  • 8

1 Answers1

1

You can continue to use Q but for iterating the first result you can use async.each (https://github.com/caolan/async#each) . In the iteratee you can perform the delete task. In the callback of the iteration resume your operation of sending. It will make your code simpler and less verbose

Golak Sarangi
  • 809
  • 7
  • 22