node.js - Node + Q with expressjs - ordered promisses -


i want execute set of functions in order written , in end release request client.

for example see mock code bellow:

router.get('/dashboard', function(req, res, next) {      var json = {items : 0}     q.fcall(       function(){          //first exec          json.items+=1;       }     ).then(       function(){          //scond exec          json.items+=1;       }     ).then(       function(){          //third exec          json.items+=1;       }     ).finally(       function(){         //do when other promises don         res.json(json);      });  } 

the function shoud executed when done.

can done q?

update think mislead you, , did not give information, because did not think relevant, is...
bringing data via mongoose, , mongoose async asd well.
goes this:

 q.fcall(         function() {             visitor.count(daterange, function(err, data) {                 json.newvisitors = data;             });         }).then(         function() {             account.count(daterange, function(err, data) {                 json.newaccounts = data;             });         }).finally(         function() {             res.json(json);         }) 

mongoose promisified. calling exec() on query gives promise. here 2 ways of doing it:

classic promises chaining:

visitor.count(daterange).exec().then(function (data) {     json.newvisitors = data;     return account.count(daterange).exec(); // return promise chaining }).then(function (data) {     json.newaccounts = data; }).then(function () {     res.json(json); }).catch(function (err) {     // handle errors }); 

or promise.all:

promise.all([     visitor.count(daterange).exec(),     account.count(daterange).exec() ]).then(function(result){     // result ordered array of promises result      json.newvisitors = result[0];     json.newaccounts = result[1]; }).catch(function (err) {     // handle errors }); 

Comments

Popular posts from this blog

gridview - Yii2 DataPorivider $totalSum for a column -

java - Suppress Jboss version details from HTTP error response -

Sass watch command compiles .scss files before full sftp upload -