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