ExpressJS 后端将请求放入队列

ash*_*shr 5 node.js promise express 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) {
        //....
      })

    })
Run Code Online (Sandbox Code Playgroud)

Ben*_*aum 5

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

var res = fn(req.body); // returns the appropriate promise
Run Code Online (Sandbox Code Playgroud)

并且您想在其中添加排队功能。您必须执行以下操作:

  • fnfnQueued这样的装饰,当fnQueued被调用时我们:
    • 为该值创建一个新的承诺。
    • 排队工作

幸运的是,这几乎是 promises 已经做的事情,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
    }
}
Run Code Online (Sandbox Code Playgroud)

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

var queuedFn = queue(fn);

express.Router().post('/tasks', function(req, res) {
    queuedFn(req.body).then(v => res.json(v), e => res.error(e));
});
Run Code Online (Sandbox Code Playgroud)