Node.js 节点+;带expressjs的Q-有序本票

Node.js 节点+;带expressjs的Q-有序本票,node.js,express,q,Node.js,Express,Q,我希望按照编写的顺序执行一组函数,并最终将请求释放给客户端 例如,请参见下面的模拟代码: router.get('/dashboard', function(req, res, next) { var json = {items : 0} Q.fcall( function(){ //first exec json.items+=1; } ).then( function(){ /

我希望按照编写的顺序执行一组函数,并最终将请求释放给客户端

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

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);
     });

}
完成所有操作后,应执行finally函数

用Q能做到吗

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

 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);
        })
是的:

然后

返回:

{"items":"ABC"}
p.S.您可能还需要调查等人:

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

现在返回:

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

猫鼬已经出现了。对查询调用
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([
    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
});

你的代码行得通吗?它是伪代码,我在寻找等效的方法来实现它。你是否尝试过这个伪代码?看起来它应该可以工作。你的代码可以按原样工作。不过,您应该使用内置的Promise,只需将
Q.fcall
替换为
Promise.resolve()。然后将
finally
替换为
then
。听起来很奇怪,最后作为第一个执行,而不是最后一个。这是一个很好的短的执行方法!您还可以使事情更加并行……在这两种情况下,当我需要执行
res.json(json)
时,问题是json永远不会返回到客户端,因此我会在一分钟后超时~。它就像
.then()
函数没有返回到client@Shazam添加
console.log(err)在catch块内,您可能有猫鼬错误。谢谢!!!你能告诉我,如果我可以避免做捕捉所有的时间,从一个地方,捕捉所有的错误,并记录它?再次感谢+1您亲身体验过,抓住任何承诺的错误是最佳做法。这个链接非常有趣:新手的错误#3显示了一段很好的代码:
.catch(console.log.bind(console))
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}
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([
    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
});