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)
当然,这很简单,假设您有一个fn返回承诺的函数。
var res = fn(req.body); // returns the appropriate promise
Run Code Online (Sandbox Code Playgroud)
并且您想在其中添加排队功能。您必须执行以下操作:
fn用fnQueued这样的装饰,当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)