Search code examples
javascriptangularjsqueuepromise

How to dynamically add functions to the queue?


I have render(value) function that I'm calling multiple times with different parameters. I need to chain calls to this function, so that it starts execution only when previous call has finished.

The function I need to chain returns a promise:

function render(value){
   var deferred = $q.defer();

   /* Some logic here */

   return deferred.promise;
}

What should I place here?

function onClick(value){
   /*
       Add render(value) to the queue. And start execution if queue is empty
   */
}

Solution

  • That's just then chaining -

    Creating the queue:

    var queue = $q.when(); 
    

    Adding a function to run on the queue:

    queue = queue.then(function(){ // need to reassign since promises are immutable.
        console.log("Added!");
    });
    

    So, in your example:

    function onClick(value){
      queue = queue.then(function(){ return render(value); });
    }