ExpressJS后端将请求放入队列

时间:2016-03-18 11:23:40

标签: node.js express promise bluebird

我有客户端发送要由服务器执行的任务,但这些请求应该像时尚一样在队列中处理。知道我怎么能这样做吗?感谢。



    express.Router().post('/tasks', function(req, res){
      //This is the task to perform. While being performed, another user
      //might send a request AND should only be processed when this is done.
      //This should also flag the pending task if it is completed.

      Promise.resolve(req.body)
      .then(function() {
      //..
      })
      .catch(function(error) {
        //....
      })

    })




1 个答案:

答案 0 :(得分:3)

当然,这很简单,假设您有一个返回承诺的函数fn

var res = fn(req.body); // returns the appropriate promise

并且您想要添加排队。你必须做类似的事情:

  • 使用fn装饰fnQueued,以便在调用fnQueued时我们:
    • 为值创建新承诺。
    • 排队工作

幸运的是,这几乎是承诺then的承诺,所以我们可以重用它而不是实现我们自己的排队逻辑:

function queue(fn) {
    var queue = Promise.resolve(); // create a queue
    // now return the decorated function
    return function(...args) {
       queue = queue.then(() => { // queue the function, assign to queue
          return fn(...args); // return the function and wait for it
       });
       return queue; // return the currently queued promise - for our argumnets
    }
}

这将让我们做类似的事情:

var queuedFn = queue(fn);

express.Router().post('/tasks', function(req, res) {
    queuedFn(req.body).then(v => res.json(v), e => res.error(e));
});
相关问题