Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ExpressJS backend put requests into a queue

I have clients sending tasks to be performed by the server but these requests should be handled in a queue like fashion. Any idea how I can do this? Thanks.

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

    })
like image 892
ashr Avatar asked Mar 18 '16 11:03

ashr


1 Answers

Sure, this is pretty simple, let's say you have a function fn that returns a promise.

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

And you want to add queueing into it. You'll have to do something like:

  • Decorate fn with a fnQueued such that when fnQueued is called we:
    • Create a new promise for the value.
    • Queue the work

Lucky for us, this is pretty much what promises already do with then so we can reuse it instead of implementing our own queueing logic:

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
    }
}

This would let us do something like:

var queuedFn = queue(fn);

express.Router().post('/tasks', function(req, res) {
    queuedFn(req.body).then(v => res.json(v), e => res.error(e));
});
like image 191
Benjamin Gruenbaum Avatar answered Sep 27 '22 23:09

Benjamin Gruenbaum