Node + Q with expressjs - ordered promisses

时间:2016-02-22 14:37:07

标签: node.js express q

我想按照它们编写的顺序执行一组函数,最后将请求发布给客户端。

例如,请参阅下面的模拟代码:

NAME IN (ACTUAL_VALUE_1,ACTUAL_VALUE_2,.., ACTUAL_VALUE_N)

当完成所有操作后,应该执行finally函数。

可以用Q吗?

更新 我想我误导了你,并没有提供所有的信息,因为我认为它不相关,但它是...... 我实际上通过mongoose提供数据,而mongoose也是异步的 所以它是这样的:

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 this when all the other promises are don
        res.json(json);
     });

}

2 个答案:

答案 0 :(得分:3)

猫鼬已经被宣传了。在查询上调用exec()会给您一个承诺。这有两种方法:

经典承诺链接:

Visitor.count(dateRange).exec().then(function (data) {
    json.newVisitors = data;
    return Account.count(dateRange).exec(); // return promise for chaining
}).then(function (data) {
    json.newAccounts = data;
}).then(function () {
    res.json(json);
}).catch(function (err) {
    // handle errors
});

或Promise.all:

Promise.all([
    Visitor.count(dateRange).exec(),
    Account.count(dateRange).exec()
]).then(function(result){
    // result is an ordered array of all the promises result 
    json.newVisitors = result[0];
    json.newAccounts = result[1];
}).catch(function (err) {
    // handle errors
});

答案 1 :(得分:1)

是的:

var path = require('path'),
    express = require('express'),
    app = express(),
    router = express.Router(),
    Q = require('q');

router.get('/dashboard', function(req, res) {

  var json = {items:''};

  Q.fcall(function() {
        json.items += 'A';
      })
      .then(function() {
        json.items += 'B';
      })
      .then(function() {
        json.items += 'C';
      })
      .finally(function() {
        res.json(json);
      });
});

app.use('/', router);

var http = require('http');

var port = process.env.PORT || '3000';
app.set('port', port);

var server = http.createServer(app);
server.listen(port);
server.on('listening', function onListening() {
      var addr = server.address();
      var bind = typeof addr === 'string'
          ? 'pipe ' + addr
          : 'port ' + addr.port;
      console.log('Listening on ' + bind);
    }
);

然后

curl localhost:3000/dashboard                                                                                                                                                                                                 

返回:

{"items":"ABC"}

P.S。您可能还想调查async-q等。人:

async.series([
  ->
    ### do some stuff ###
    Q 'one'
  ->
    ### do some more stuff ... ###
    Q 'two'
]).then (results) ->
    ### results is now equal to ['one', 'two'] ###
    doStuff()
  .done()

### an example using an object instead of an array ###
async.series({
  one: -> Q.delay(200).thenResolve(1)
  two: -> Q.delay(100).thenResolve(2)
}).then (results) ->
    ### results is now equal to: {one: 1, two: 2} ###
    doStuff()
  .done()

更新(有点强迫,我只会使用async):

var path = require('path'),
    express = require('express'),
    app = express(),
    logger = require('morgan'),
    router = express.Router(),
    Q = require('q'),
    async = require('async-q');

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));

router.get('/dashboard', function(req, res) {

  var json = {};

  async.series({
        newVisitors: function() {
          return Q.Promise(function(resolve,reject) {
            console.log(arguments);
            Visitor.count(dateRange, function(err, data) {
              if(err) return reject(err);
              resolve(data);
            });
          });
        },
        newAccounts: function() {
          return Q.Promise(function(resolve,reject) {
            Account.count(dateRange, function(err, data) {
              if(err) return reject(err);
              resolve(data);
            });
          });
        }
  })
      .then(function(json) {
        res.json(json);
      });
});

app.use('/', router);

var http = require('http');

var port = process.env.PORT || '3000';
app.set('port', port);

var server = http.createServer(app);
server.listen(port);
server.on('listening', function onListening() {
      var addr = server.address();
      var bind = typeof addr === 'string'
          ? 'pipe ' + addr
          : 'port ' + addr.port;
      console.log('Listening on ' + bind);
    }
);

现在返回:

{"newVisitors": 1,"newAccounts":2}