node.js - ExpressJS 后端将请求放入队列

标签 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) {
        //....
      })

    })

最佳答案

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

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

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

  • fnQueued 装饰 fn 这样当 fnQueued 被调用时我们:
    • 为值(value)创造新的 promise 。
    • 排队工作

幸运的是,这几乎就是 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
    }
}

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

var queuedFn = queue(fn);

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

关于node.js - ExpressJS 后端将请求放入队列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36083121/

相关文章:

javascript - 我在哪里可以获得所有 native Node 模块的数组?

node.js - 存储静态内容时应用程序大小重要吗?

node.js - 如果一次运行超过 4 个测试,Mocha 测试超时

javascript - 无论如何,有没有在jade中编写服务器端nodejs

javascript - 如何等待 Promise 中的函数?

javascript - Promise 不会解析为 true 或 false

javascript - 在 Angular 中导入和使用外部 JS 库

javascript - 如何在 Heroku 中结合 node.js 和 Java buildpack

node.js - .auth().verifyIdToken 错误 : Firebase ID token has incorrect algorithm. 预期 "none"但得到 "RS256"

node.js - 类型错误 : Cannot call method 'then' of undefined