node.jsexpresspromisebluebird

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

    })


Solution

  • 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:

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