How to name a Q promise as part of a promise chain

I need help notify()with the promise chain.

I have 3 promise to the basic functions connect(), send(cmd), disconnect(). Now I would like to write another function for transferring these calls as follows with a progress notification.

function bombard() {
 return connect()
  .then(function () {
    var cmds = [/*many commands in string*/];
    var promises = _.map(cmds, function (cmd) {
     var deferred = Q.defer();
     deferred.notify(cmd);
     send(cmd).then(function (result) {
      deferred.resovle(result);
     });
     return deferred.promise;
    });
    return Q.all(promises);
  })
 .finally(function () { return disconnect() })
}

Perform such a function

bombard.then(onResolve, onReject, function (obj) {
 console.log(ob);
});

I assumed that I was receiving a notification for each team that I sent. However, it does not work as I expected. I get nothing.

While I believe that this is due to the fact that these notifications are not subject to an external promise, I have no idea how to distribute these notifications on Q or wrap the chain promises: connect, send, disconnectin one pending subject.

thank

+4
1

.

! API- Q v2, , Bluebird, ECMAScript 6. , promises .

API . , , promises, ,

, IProgress #. Q.delay() , , ,

function connect(iProgress){
    return Q.delay(1000).then(function(res){
        iProgress(0.5,"Connecting to Database");
    }).delay(1000).then(function(res){
        iProgress(0.5,"Done Connecting");
    });

} 

function send(data,iProgress){
     return Q.delay(200*Math.random() + 200).then(function(res){
         iProgress(0.33, "Sent First Element");
     }).delay(200*Math.random() + 400).then(function(){
         iProgress(0.33, "Sent second Element");
     }).delay(200*Math.random() + 500).then(function(){
         iProgress(0.33, "Done sending!");
     });
}
// disconnect is similar

, promises, :

function aggregateProgress(num){
     var total = 0;
     return function(progression,message){
          total += progression;
          console.log("Progressed ", ((total/num)*100).toFixed(2)+"%" );
          console.log("Got message",message);
     }
}

:

// bombard can accept iProgress itself if it needs to propagate it
function bombard() {
 var notify = aggregateProgress(cmds.length+1);
 return connect(notify)
  .then(function () {
    var cmds = [/*many commands in string*/];
    return Q.all(cmds.map(function(command){ return send(command,notify); }));
  });
}

,

+11

Source: https://habr.com/ru/post/1542014/


All Articles