jquery Deferred
三个异步任务, 顺序执行
var step1 = function(){ var def = $.Deferred(); setTimeout(function(){ console.log('我是第一个任务'); def.resolve(); },3000) return def.promise(); } var step2 = function(){ var def = $.Deferred(); setTimeout(function(){ console.log('我是第二个任务'); def.resolve(); },5000) return def.promise(); } var step3 = function(){ var def = $.Deferred(); setTimeout(function(){ console.log('我是第三个任务'); def.resolve(); },1000) return def.promise(); } step1().then(step2).then(step3)
三个任务 最后一个等待第一个 第二个完成后才触发
// 异步执行 var step1 = function(){ var def = $.Deferred(); setTimeout(function(){ console.log('我是第一个任务'); def.resolve(); },3000) return def.promise(); } var step2 = function(){ var def = $.Deferred(); setTimeout(function(){ console.log('我是第二个任务'); def.resolve(); },1000) return def.promise(); } var step3 = function(){ var def = $.Deferred(); setTimeout(function(){ console.log('我是第三个任务'); def.resolve(); },300) return def.promise(); } $.when(step1(), step2()).then(step3);
切忌浮躁