官术网_书友最值得收藏!

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);
  });
主站蜘蛛池模板: 襄樊市| 长宁县| 宁晋县| 武平县| 棋牌| 江北区| 万州区| 宁城县| 陆丰市| 临沧市| 长宁县| 吉安县| 勐海县| 望谟县| 罗山县| 吉木乃县| 宁明县| 潢川县| 上饶县| 盐城市| 聂荣县| 庆阳市| 龙口市| 平远县| 惠州市| 滦平县| 太康县| 罗城| 凤翔县| 闽清县| 青州市| 赤壁市| 青阳县| 揭阳市| 北碚区| 遂平县| 伊春市| 阜新市| 勃利县| 屏山县| 宾阳县|