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) {
        //....
      })
    })
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:
fn with a fnQueued such that when fnQueued is called we:
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));
});
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With