ExpressJS后端将请求放入队列中
我有客户端发送任务由服务器执行,但这些请求应该像时尚一样处理队列。 任何想法我怎么能做到这一点? 谢谢。
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的函数。
var res = fn(req.body); // returns the appropriate promise
你想添加排队到它。 你将不得不做一些事情:
- 用
fnQueued
装饰fn
,当fnQueued
被调用时,我们:- 为价值创造新的承诺。
- 排队工作
对我们来说幸运的是,这几乎已经做了什么,所以我们可以重用它,而不是实现我们自己的排队逻辑:
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)); });