javascript - jquery combining chaining when done when done and so on ... when then -


i have structure below need executed in order:

var task1, task2, task3, last;  initialize = $.when(function(){ ...initializing... }).done(function(){ ..initialization completed.. });  task1 = initialize.when(function(){ ..doing task1.. }).done(function(){ ..task1 completed.. });  task2 = task1.when(function(){ ..doing task2.. }).done(function(){ ..task2 completed.. });  task3 = task2.when(function(){ ..doing task3.. }).done(function(){ ..task3 completed.. });  last  = task3.when(function(){ ..doing last.. }).then(function(){ ..last completed.. }); 

how jquery-1.10.2?

considering above example console output be:

initializing initialization completed doing task1 task1 completed doing task2 task2 completed doing task3 task3 completed doing last last completed 

when working asynchronous tasks need executed in order can wrapp them $.deferred , chain them using deffered.then():

function init() {     console.log("initializing"); }  function dotask1() {      var d = $.deferred();      console.log("synchronous part of task 1");      settimeout(function() {          console.log("asynchronous part of task 1");          d.resolve() }, 5000);      return d; }  function dotask2(resfromtask1) {     var d = $.deferred();      console.log("task2");     settimeout(function() {          console.log("asynchronous part of task 2");          d.resolve() }, 5000);       return d; }  function dolast() {     console.log("last task"); }  $.when(init()).then(dotask1).then(dotask2).done(dolast); 

note dolast function get's called when deffered returned dotask2 resolved. if instance wanted run synchronous function after dotask1 before dotask2 need added this:

$.when(init()).then(dotask1).done(function() {         console.log("new synchronous function");     }).then(dotask2).done(dolast); 

now both dotask2 , anonymous function run when dotask1's deferred object resolved. if anonymous function moved after dotask2:

$.when(init()).then(dotask1).then(dotask2).done(function() {         console.log("new synchronous function");     }).done(dolast); 

then anonymous function , dolast function both run when deferred object returned dotask2 finishes.


Comments

Popular posts from this blog

c# - How Configure Devart dotConnect for SQLite Code First? -

java - Copying object fields -

c++ - Clear the memory after returning a vector in a function -