Common sequencing patterns

Promise and deferred enables us to represent simple tasks combined with complex tasks to a fine-grained control over their sequences.

As mentioned earlier, deferred is an object that represents work that is not being done yet and promise is an object representing a value that is currently unknown. This concept helps us write asynchronous JavaScript, similar to how we write synchronous code.

Promises make it comparatively easy to abstract small pieces of functionality shared across multiple asynchronous tasks. Let's take a look at the most common sequencing patterns that promises makes easier:

  • Stacked
  • Parallel
  • Sequential

Stacked

Stacked binds multiple handlers anywhere in the application to the same promise event. This helps us bind a number of handlers in a cleaner way so that it gives control to sequence within our code. Here is a sample for stacked and bind handlers:

var req = $.ajax(url);
  req.done(function () {
      console.log('your assigned Request has been completed'),
  });

  //Somewhere in the application
  req.done(function (retrievedData) {
      $('#contentPlaceholder').html(retrievedData);
  });

Parallel

Parallel simply asks multiple promises to return a single promise, which alerts of their multiple completion.

With the parallel sequence, you can write multiple promises to return a single promise. In a parallel sequence, an array of asynchronous tasks are executed concurrently and return a single promise when all the tasks have succeeded or rejected with an error in case of failure.

A general code snippet that shows how parallel sequence returns a single promise is shown as follows:

$.when(task01, task02).done(function () {
      console.log('taskOne and taskTwo were finished'),
});

For a more clear understanding, here is a sample function that processes the parallel sequence:

function testPromiseParallelSequence(tasks)
{
    
    var results = [];  //an array of async tasks 
    
    //tasks.map() will map all the return call was made.
    
    taskPromises = tasks.map(function(task) 
    {
        return task();
    }); //returning all the promise

Sequential

Actions need to be in sequence if the output of one action is an input to another. HTTP requests are such a case where one action is an input to the other. Sequence also enables you to transfer the control of one part of the code to the other.

It executes tasks in a sequential order that is defined by the need of the application, or the scope of the tasks that need to be queued in order to be served.

Here is a generic example in which one sequence processes and passes control to the other as an input:

// seq1 and seq2 represents sequence one and two respectively
var seq1, seq2, url; 
url = 'http://sampleurl.com;
seq1 = $.ajax(url);
   seq2 = seq1.then(

    function (data) {
        var def = new $.Deferred();

        setTimeout(function () {
            console.log('Request completed'),
            def.resolve();
        },1000);

      return def.promise();
  },
      
    function (err) {
        console.log('sequence 1 failed: Ajax request'),
    }
  );
  seq2.done(function () {
      console.log('Sequence completed')
      setTimeout("console.log('end')",500);
  });
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.223.114.142