SlideShare a Scribd company logo
1 of 58
Download to read offline
daiying.zhang
jQuery延迟对象
Deferred Object
event
so easy…
More then one
:)
document.getElementById('foo').addEventListener('click', function(){
/* something ...*/
});
document.getElementById('foo').addEventListener('click', function(){
/* something else ...*/
});
then..
document.getElementById('foo').addEventListener('click', function(){
/* something ...*/
});
document.getElementById('foo').addEventListener('click', function(){
/* something else ...*/
});
document.getElementById('foo').addEventListener('click', function(){
/* something more ...*/
});
document.getElementById('foo').addEventListener('click', function(){
/* something more then more ...*/
});
document.getElementById('foo').addEventListener('click', function(){
/* oh my god ! */
});
var img = new Image();
img.onload = function(){
    //...
    alert('load');
}
img.src = "http://localhost/aaa.jpg?t=" + Math.random();
// ...
setTimeout(function(){
    alert(img.complete)
    img.onload = function(){
        // todo something
        alert('ok');
    }
}, 3000)
then..
document.getElementById('foo').addEventListener('click', function(){
/* something ...*/
});
document.getElementById('foo').addEventListener('click', function(){
/* something else ...*/
});
document.getElementById('foo').addEventListener('click', function(){
/* something more ...*/
});
document.getElementById('foo').addEventListener('click', function(){
/* something more then more ...*/
});
document.getElementById('foo').addEventListener('click', function(){
/* oh my god ! */
});
async
顺序
?
:(
?
:)
setTimeout(function(){
/* this may takes a long time*/
var value = foo(65535);
/* call it here */
calc(result);
}, 5000)
//calc(result);
then…
step1(1, function(){
step2(2, function(){
setp3(3, function(){
setp4(4, function(){
// Oh my god !
})
})
}
})
“Callback hell”
代码变复杂	 
不利于模块化	 
可维护性差	 
紧耦合
Ajax
$.ajax({
url: 'http://www.xxx.com/api',
type: 'POST',
success: function(json){
/* do something */
},
error: function(msg){
/* get an error */
}
})
Exception
try{
setTimeout(function(){
throw new Error(':(')
}, 0)
}catch(e){
alert('get an error');
}
Promise/A
$
jQuery is coming…
Deferred / Callbacks
Callbacks
1、jQuery 1.7 版本中新增的
2、jQuery.Callbacks() 函数返回的对象
3、对象对管理回调列表提供了强⼤大的⽅方式
4、能够增加、删除、触发、禁⽤用回调函数
5、⽀支持不同的参数来控制回调执⾏行
// todo demo
Deferred
一个可链式调用的工具对象,管理回调,简化异步操作	 
可以注册多个回调,调用回调队列,并且传播任何同
步或异步函数的状态	 
三种状态:pending|resolved|rejected	 
状态改变后无法再次修改	 
拥有一个promise对象
API
var def = jQuery.Deferred();
def.done(function(){ console.warn('done'); });
def.fail(function(){ console.warn('fail'); });
console.warn('def.state() ==>', def.state());
def.reject();
console.warn('def.state() ==>', def.state());
var def = jQuery.Deferred();
def.then(function(){ console.warn('done'); },
function(){ console.warn('fail'); });
console.warn('def.state() ==>', def.state());
def.reject();
console.warn('def.state() ==>', def.state());
deferred.then()
deferred.then(fnDone[,	 fnFail[,	 fnPro]])
分别调用deferred的	 
.done(),	 .fail(),	 .progress()	 
添加相应回调函数
return	 this
start
end
version : 1.5.x/1.6.x/1.7.x
创建新Deferred对象	 
(newDefer)
分别调用deferred的	 
.done(),	 .fail(),	 .progress()	 
添加相应回调函数
return	 newDefer.promise()
start
end
version : 1.8.x+
职责:
1、执⾏行回掉函数
2、改变新的Deferred对象的状态
3、返回新的Deferred对象
deferred.then/pipe
分别调用deferred的	 
.done(),	 .fail(),	 .progress()	 
添加相应回调函数
return	 this
start
end
version : 1.5.x/1.6.x/1.7.x
then
创建新Deferred
对象	 
(newDefer)
分别调用deferred的	 
.done(),	 .fail(),	 .progress()	 
添加相应回调函数
return	 
newDefer.promise()
start
end
version : 1.6.x/1.7.x
pipe
创建新Deferred
对象	 
(newDefer)
分别调用deferred的	 
.done(),	 .fail(),	 .progress()	 
添加相应回调函数
return	 
newDefer.promise()
start
end
version : 1.8.x+
then
d1
done function
fail function
state “pending”
… …
doneList Array
failList Array
doneList
0 changeState
1 failList.disable
2 progress.lock
donList和failList实际上不是d1的属性,只是一个局部变量,	 
为了演示方便,加入到d1
d1
done function
fail function
state “pending”
… …
doneList Array
failList Array
doneList
0 changeState
1 failList.disable
2 progress.lock
3 function	 
doneList
0 changeState
1 doneList.disable
2 progress.lock
d2
done function
fail function
then function
… …
doneList Array
failList Array
f1
f2
f3
failList
0 changeState
1 failList.disable
2 progress.lock
d1
done function
then function
state “pending”
… …
doneList Array
failList Array
doneList
0 changeState
1 failList.disable
2 progress.lock
3 function	 
doneList
0 changeState
1 doneList.disable
2 progress.lock
d2
done function
fail function
then function
… …
doneList Array
failList Array
f1
f2
f3
failList
0 changeState
1 failList.disable
2 progress.lock
start
call	 fn	 &	 get	 result	 
(returned)
isPromise
(returned)	 
end
returned.promise()	 
.then(…)
newDefer[resolve
With|rejectWith|
progressWith]
Y
N
d1
done function
fail function
then function
… …
doneList Array
failList Array
doneList
0 changeState
1 failList.disable
2 progress.lock
3 function	 
doneList
0 changeState
1 doneList.disable
2 progress.lock
3 function	 
d2
done function
fail function
then function
… …
doneList Array
failList Array
f1
f2
f3
failList
0 changeState
1 failList.disable
2 progress.lock
3 function
d1
done function
then function
state “resolved”
… …
doneList Array
failList Array
doneList
0 changeState
1 failList.disable
2 progress.lock
3 function	 
doneList
0 changeState
1 doneList.disable
2 progress.lock
3 function	 
d2
done function
fail function
then function
… …
doneList Array
failList Array
f1
f2
f3
failList
0 changeState
1 failList.disable
2 progress.lock
3 function	 
isPromise(returned	 =	 d)	 ==	 true
d.then(d2.resolve,	 d2.reject)
d2.reject()
// TODO ….
:)
d1
done function
fail function
then function
… …
doneList Array
failList Array
failList
0 changeState
1 doneList.disable
2 progress.lock
3 undefined
doneList
0 changeState
1 doneList.disable
2 progress.lock
3 function	 
d2
done function
fail function
then function
… …
doneList Array
failList Array
f1
f2
f3
faiList
0 changeState
1 failList.disable
2 progress.lock
3 function	 
returned	 =	 fnFail	 &&	 returned
returned	 ==	 false
d2.rejectWith()
                var deferred = $.Deferred();
                deferred.then(function(res){
                    console.warn('ok 1');
                },function(err){
                    console.warn('err 1');
                })
                .then(function(res){
                    console.warn('ok 2');
                },function(err){
                    console.warn('err 2');
                })
                .then(function(res){
                    console.warn('ok 3');
                },function(err){
                    console.warn('err 3');
                });         
deferred.reject();
p(deferred)
deferred.done/fail/
progress()
done() or then() ?
顺序 / 值
// then
var def = $.Deferred();
def.then(
    function(val){ console.warn('done +1 ==>', val); return val + 1 }
).then(
    function(val){ console.warn('done +2 ==>', val); return val + 2 }
).then(
    function(val){ console.warn('done +3 ==>', val); return val + 3 }
)
def.resolve(1)
// done
var def = $.Deferred();
def.done(
    function(val){ console.warn('done +1 ==>', val); return val + 1 }
).done(
    function(val){ console.warn('done +2 ==>', val); return val + 2 }
).done(
    function(val){ console.warn('done +3 ==>', val); return val + 3 }
)
def.resolve(1)
// then async
var def = $.Deferred();
def.then( // d1
deferred.promise()
返回一个Deferred的只读对象
var def = $.Deferred();
p(def)
Deferred or Promise ?
Read Only
jQuery.when()
提供一种方法来执行一个或多个对象的回调函数,	 
Deferred(延迟)对象通常表示异步事件。
use
// no-deferred object
var obj = {
  a:1,
  b:2
}
function func1(obj){
  console.warn(obj)
}
function func2(obj){
  console.warn(obj)
}
func1(obj);
func2(obj);
// deferred object
// deferred object
var def1 = $.Deferred();
var def2 = $.Deferred();
function func1(obj){
  console.warn(obj)
}
function func2(obj){
  console.warn(obj)
}
Thx
:)

More Related Content

What's hot

Student management system
Student management systemStudent management system
Student management systemgeetika goyal
 
The next step, part 2
The next step, part 2The next step, part 2
The next step, part 2Pat Cavit
 
Redux saga: managing your side effects. Also: generators in es6
Redux saga: managing your side effects. Also: generators in es6Redux saga: managing your side effects. Also: generators in es6
Redux saga: managing your side effects. Also: generators in es6Ignacio Martín
 
Js 单元测试框架介绍
Js 单元测试框架介绍Js 单元测试框架介绍
Js 单元测试框架介绍louieuser
 
Wwe Management System
Wwe Management SystemWwe Management System
Wwe Management SystemNeerajMudgal1
 
05 JavaScript #burningkeyboards
05 JavaScript #burningkeyboards05 JavaScript #burningkeyboards
05 JavaScript #burningkeyboardsDenis Ristic
 
06 jQuery #burningkeyboards
06 jQuery  #burningkeyboards06 jQuery  #burningkeyboards
06 jQuery #burningkeyboardsDenis Ristic
 
PhpUnit - The most unknown Parts
PhpUnit - The most unknown PartsPhpUnit - The most unknown Parts
PhpUnit - The most unknown PartsBastian Feder
 
The Ring programming language version 1.6 book - Part 34 of 189
The Ring programming language version 1.6 book - Part 34 of 189The Ring programming language version 1.6 book - Part 34 of 189
The Ring programming language version 1.6 book - Part 34 of 189Mahmoud Samir Fayed
 
UI 모듈화로 워라밸 지키기
UI 모듈화로 워라밸 지키기UI 모듈화로 워라밸 지키기
UI 모듈화로 워라밸 지키기NAVER SHOPPING
 
2020 Droid Knights CustomLint 적용기
2020 Droid Knights CustomLint 적용기2020 Droid Knights CustomLint 적용기
2020 Droid Knights CustomLint 적용기Insung Hwang
 
The redux saga begins
The redux saga beginsThe redux saga begins
The redux saga beginsDaniel Franz
 
2019-10-05 - Untangled - Voxxed days ticino
2019-10-05 - Untangled - Voxxed days ticino2019-10-05 - Untangled - Voxxed days ticino
2019-10-05 - Untangled - Voxxed days ticinoArnaud Bos
 
To Err Is Human
To Err Is HumanTo Err Is Human
To Err Is HumanAlex Liu
 

What's hot (19)

Student management system
Student management systemStudent management system
Student management system
 
The next step, part 2
The next step, part 2The next step, part 2
The next step, part 2
 
Redux saga: managing your side effects. Also: generators in es6
Redux saga: managing your side effects. Also: generators in es6Redux saga: managing your side effects. Also: generators in es6
Redux saga: managing your side effects. Also: generators in es6
 
Java Cheat Sheet
Java Cheat SheetJava Cheat Sheet
Java Cheat Sheet
 
Js 单元测试框架介绍
Js 单元测试框架介绍Js 单元测试框架介绍
Js 单元测试框架介绍
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 
Wwe Management System
Wwe Management SystemWwe Management System
Wwe Management System
 
05 JavaScript #burningkeyboards
05 JavaScript #burningkeyboards05 JavaScript #burningkeyboards
05 JavaScript #burningkeyboards
 
06 jQuery #burningkeyboards
06 jQuery  #burningkeyboards06 jQuery  #burningkeyboards
06 jQuery #burningkeyboards
 
PhpUnit - The most unknown Parts
PhpUnit - The most unknown PartsPhpUnit - The most unknown Parts
PhpUnit - The most unknown Parts
 
The Ring programming language version 1.6 book - Part 34 of 189
The Ring programming language version 1.6 book - Part 34 of 189The Ring programming language version 1.6 book - Part 34 of 189
The Ring programming language version 1.6 book - Part 34 of 189
 
UI 모듈화로 워라밸 지키기
UI 모듈화로 워라밸 지키기UI 모듈화로 워라밸 지키기
UI 모듈화로 워라밸 지키기
 
2020 Droid Knights CustomLint 적용기
2020 Droid Knights CustomLint 적용기2020 Droid Knights CustomLint 적용기
2020 Droid Knights CustomLint 적용기
 
Ruby tricks2
Ruby tricks2Ruby tricks2
Ruby tricks2
 
The redux saga begins
The redux saga beginsThe redux saga begins
The redux saga begins
 
2019-10-05 - Untangled - Voxxed days ticino
2019-10-05 - Untangled - Voxxed days ticino2019-10-05 - Untangled - Voxxed days ticino
2019-10-05 - Untangled - Voxxed days ticino
 
To Err Is Human
To Err Is HumanTo Err Is Human
To Err Is Human
 
Introduction to Groovy
Introduction to GroovyIntroduction to Groovy
Introduction to Groovy
 
Quiniela
QuinielaQuiniela
Quiniela
 

Viewers also liked

Software Defined Batteries - Synopsis of Microsoft Researchers Project
Software Defined Batteries - Synopsis of Microsoft Researchers ProjectSoftware Defined Batteries - Synopsis of Microsoft Researchers Project
Software Defined Batteries - Synopsis of Microsoft Researchers ProjectWinBuzzer
 
Rookie Mistakes and Resources AARP TUG
Rookie Mistakes and Resources AARP TUGRookie Mistakes and Resources AARP TUG
Rookie Mistakes and Resources AARP TUGEmily Kund
 
Study of talc filled polypropylene a concept for
Study of talc filled polypropylene  a concept forStudy of talc filled polypropylene  a concept for
Study of talc filled polypropylene a concept foreSAT Publishing House
 
An intelligent hybrid control for paper machine
An intelligent hybrid control for paper machineAn intelligent hybrid control for paper machine
An intelligent hybrid control for paper machineeSAT Publishing House
 
Oscillatory motion control of hinged body using controller
Oscillatory motion control of hinged body using controllerOscillatory motion control of hinged body using controller
Oscillatory motion control of hinged body using controllereSAT Publishing House
 
樂活華岡懶人包
樂活華岡懶人包樂活華岡懶人包
樂活華岡懶人包pccucufc
 
Patnent Information services
Patnent Information servicesPatnent Information services
Patnent Information servicesLihua Gao
 
Experimental investigation of heat transfer through
Experimental investigation of heat transfer throughExperimental investigation of heat transfer through
Experimental investigation of heat transfer througheSAT Publishing House
 
8/22 國際研習會簡報_workshop presentation
8/22 國際研習會簡報_workshop presentation8/22 國際研習會簡報_workshop presentation
8/22 國際研習會簡報_workshop presentationCDRI_snowshih
 
Network topology
Network topologyNetwork topology
Network topologyJency Pj
 
Deber de informatica
Deber de informaticaDeber de informatica
Deber de informaticakelvinmaster4
 
Bounds on double domination in squares of graphs
Bounds on double domination in squares of graphsBounds on double domination in squares of graphs
Bounds on double domination in squares of graphseSAT Publishing House
 
A mathematical model for determining the optimal size
A mathematical model for determining the optimal sizeA mathematical model for determining the optimal size
A mathematical model for determining the optimal sizeeSAT Publishing House
 
ITIL Processes V2.0D
ITIL Processes V2.0DITIL Processes V2.0D
ITIL Processes V2.0DKaran Saiya
 
Digital Sports Coaching Business Slide Pitch Framework
Digital Sports Coaching Business Slide Pitch FrameworkDigital Sports Coaching Business Slide Pitch Framework
Digital Sports Coaching Business Slide Pitch FrameworkAbel Sports Management
 
Delay efficient broadcast scheduling for critical event monitoring in wireles...
Delay efficient broadcast scheduling for critical event monitoring in wireles...Delay efficient broadcast scheduling for critical event monitoring in wireles...
Delay efficient broadcast scheduling for critical event monitoring in wireles...eSAT Publishing House
 

Viewers also liked (16)

Software Defined Batteries - Synopsis of Microsoft Researchers Project
Software Defined Batteries - Synopsis of Microsoft Researchers ProjectSoftware Defined Batteries - Synopsis of Microsoft Researchers Project
Software Defined Batteries - Synopsis of Microsoft Researchers Project
 
Rookie Mistakes and Resources AARP TUG
Rookie Mistakes and Resources AARP TUGRookie Mistakes and Resources AARP TUG
Rookie Mistakes and Resources AARP TUG
 
Study of talc filled polypropylene a concept for
Study of talc filled polypropylene  a concept forStudy of talc filled polypropylene  a concept for
Study of talc filled polypropylene a concept for
 
An intelligent hybrid control for paper machine
An intelligent hybrid control for paper machineAn intelligent hybrid control for paper machine
An intelligent hybrid control for paper machine
 
Oscillatory motion control of hinged body using controller
Oscillatory motion control of hinged body using controllerOscillatory motion control of hinged body using controller
Oscillatory motion control of hinged body using controller
 
樂活華岡懶人包
樂活華岡懶人包樂活華岡懶人包
樂活華岡懶人包
 
Patnent Information services
Patnent Information servicesPatnent Information services
Patnent Information services
 
Experimental investigation of heat transfer through
Experimental investigation of heat transfer throughExperimental investigation of heat transfer through
Experimental investigation of heat transfer through
 
8/22 國際研習會簡報_workshop presentation
8/22 國際研習會簡報_workshop presentation8/22 國際研習會簡報_workshop presentation
8/22 國際研習會簡報_workshop presentation
 
Network topology
Network topologyNetwork topology
Network topology
 
Deber de informatica
Deber de informaticaDeber de informatica
Deber de informatica
 
Bounds on double domination in squares of graphs
Bounds on double domination in squares of graphsBounds on double domination in squares of graphs
Bounds on double domination in squares of graphs
 
A mathematical model for determining the optimal size
A mathematical model for determining the optimal sizeA mathematical model for determining the optimal size
A mathematical model for determining the optimal size
 
ITIL Processes V2.0D
ITIL Processes V2.0DITIL Processes V2.0D
ITIL Processes V2.0D
 
Digital Sports Coaching Business Slide Pitch Framework
Digital Sports Coaching Business Slide Pitch FrameworkDigital Sports Coaching Business Slide Pitch Framework
Digital Sports Coaching Business Slide Pitch Framework
 
Delay efficient broadcast scheduling for critical event monitoring in wireles...
Delay efficient broadcast scheduling for critical event monitoring in wireles...Delay efficient broadcast scheduling for critical event monitoring in wireles...
Delay efficient broadcast scheduling for critical event monitoring in wireles...
 

Similar to Deferred

jQuery: out with the old, in with the new
jQuery: out with the old, in with the newjQuery: out with the old, in with the new
jQuery: out with the old, in with the newRemy Sharp
 
Advanced jQuery
Advanced jQueryAdvanced jQuery
Advanced jQuerysergioafp
 
How DRY impacts JavaScript performance // Faster JavaScript execution for the...
How DRY impacts JavaScript performance // Faster JavaScript execution for the...How DRY impacts JavaScript performance // Faster JavaScript execution for the...
How DRY impacts JavaScript performance // Faster JavaScript execution for the...Mathias Bynens
 
Think Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSThink Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSAdam L Barrett
 
Web Optimization Summit: Coding for Performance
Web Optimization Summit: Coding for PerformanceWeb Optimization Summit: Coding for Performance
Web Optimization Summit: Coding for Performancejohndaviddalton
 
Intro to Advanced JavaScript
Intro to Advanced JavaScriptIntro to Advanced JavaScript
Intro to Advanced JavaScriptryanstout
 
[removed] $file, removeRemove}, list #su.docx
[removed] $file, removeRemove}, list #su.docx[removed] $file, removeRemove}, list #su.docx
[removed] $file, removeRemove}, list #su.docxgerardkortney
 
JavaScript Functions
JavaScript FunctionsJavaScript Functions
JavaScript FunctionsColin DeCarlo
 
Javascript & Ajax Basics
Javascript & Ajax BasicsJavascript & Ajax Basics
Javascript & Ajax BasicsRichard Paul
 
Object-Oriented JavaScript
Object-Oriented JavaScriptObject-Oriented JavaScript
Object-Oriented JavaScriptkvangork
 
Object-Oriented Javascript
Object-Oriented JavascriptObject-Oriented Javascript
Object-Oriented Javascriptkvangork
 
Javascript: the important bits
Javascript: the important bitsJavascript: the important bits
Javascript: the important bitsChris Saylor
 
Ten useful JavaScript tips & best practices
Ten useful JavaScript tips & best practicesTen useful JavaScript tips & best practices
Ten useful JavaScript tips & best practicesAnkit Rastogi
 

Similar to Deferred (20)

jQuery: out with the old, in with the new
jQuery: out with the old, in with the newjQuery: out with the old, in with the new
jQuery: out with the old, in with the new
 
Advanced jQuery
Advanced jQueryAdvanced jQuery
Advanced jQuery
 
ES6 generators
ES6 generatorsES6 generators
ES6 generators
 
EcmaScript 6
EcmaScript 6 EcmaScript 6
EcmaScript 6
 
How DRY impacts JavaScript performance // Faster JavaScript execution for the...
How DRY impacts JavaScript performance // Faster JavaScript execution for the...How DRY impacts JavaScript performance // Faster JavaScript execution for the...
How DRY impacts JavaScript performance // Faster JavaScript execution for the...
 
Think Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSThink Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJS
 
Web Optimization Summit: Coding for Performance
Web Optimization Summit: Coding for PerformanceWeb Optimization Summit: Coding for Performance
Web Optimization Summit: Coding for Performance
 
jQuery: Events, Animation, Ajax
jQuery: Events, Animation, AjaxjQuery: Events, Animation, Ajax
jQuery: Events, Animation, Ajax
 
Intro to Advanced JavaScript
Intro to Advanced JavaScriptIntro to Advanced JavaScript
Intro to Advanced JavaScript
 
[removed] $file, removeRemove}, list #su.docx
[removed] $file, removeRemove}, list #su.docx[removed] $file, removeRemove}, list #su.docx
[removed] $file, removeRemove}, list #su.docx
 
jQuery secrets
jQuery secretsjQuery secrets
jQuery secrets
 
JavaScript Functions
JavaScript FunctionsJavaScript Functions
JavaScript Functions
 
JavaScript patterns
JavaScript patternsJavaScript patterns
JavaScript patterns
 
Javascript & Ajax Basics
Javascript & Ajax BasicsJavascript & Ajax Basics
Javascript & Ajax Basics
 
Object-Oriented JavaScript
Object-Oriented JavaScriptObject-Oriented JavaScript
Object-Oriented JavaScript
 
Object-Oriented Javascript
Object-Oriented JavascriptObject-Oriented Javascript
Object-Oriented Javascript
 
Events
EventsEvents
Events
 
Javascript: the important bits
Javascript: the important bitsJavascript: the important bits
Javascript: the important bits
 
Ten useful JavaScript tips & best practices
Ten useful JavaScript tips & best practicesTen useful JavaScript tips & best practices
Ten useful JavaScript tips & best practices
 
Javascript
JavascriptJavascript
Javascript
 

Recently uploaded

%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyviewmasabamasaba
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...masabamasaba
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...masabamasaba
 
What Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the SituationWhat Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the SituationJuha-Pekka Tolvanen
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024VictoriaMetrics
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrandmasabamasaba
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in sowetomasabamasaba
 
WSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park masabamasaba
 
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburgmasabamasaba
 
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benonimasabamasaba
 
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...chiefasafspells
 
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...WSO2
 
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfonteinmasabamasaba
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension AidPhilip Schwarz
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2
 
WSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaSWSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaSWSO2
 

Recently uploaded (20)

%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
What Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the SituationWhat Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the Situation
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto
 
WSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go Platformless
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
 
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
 
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
 
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
 
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
 
WSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaSWSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaS
 

Deferred

  • 5. :) document.getElementById('foo').addEventListener('click', function(){ /* something ...*/ }); document.getElementById('foo').addEventListener('click', function(){ /* something else ...*/ });
  • 6. then.. document.getElementById('foo').addEventListener('click', function(){ /* something ...*/ }); document.getElementById('foo').addEventListener('click', function(){ /* something else ...*/ }); document.getElementById('foo').addEventListener('click', function(){ /* something more ...*/ }); document.getElementById('foo').addEventListener('click', function(){ /* something more then more ...*/ }); document.getElementById('foo').addEventListener('click', function(){ /* oh my god ! */ });
  • 7. var img = new Image(); img.onload = function(){     //...     alert('load'); } img.src = "http://localhost/aaa.jpg?t=" + Math.random(); // ... setTimeout(function(){     alert(img.complete)     img.onload = function(){         // todo something         alert('ok');     } }, 3000)
  • 8. then.. document.getElementById('foo').addEventListener('click', function(){ /* something ...*/ }); document.getElementById('foo').addEventListener('click', function(){ /* something else ...*/ }); document.getElementById('foo').addEventListener('click', function(){ /* something more ...*/ }); document.getElementById('foo').addEventListener('click', function(){ /* something more then more ...*/ }); document.getElementById('foo').addEventListener('click', function(){ /* oh my god ! */ });
  • 10. ?
  • 11. :(
  • 12. ?
  • 13. :) setTimeout(function(){ /* this may takes a long time*/ var value = foo(65535); /* call it here */ calc(result); }, 5000) //calc(result);
  • 14. then… step1(1, function(){ step2(2, function(){ setp3(3, function(){ setp4(4, function(){ // Oh my god ! }) }) } })
  • 17. Ajax
  • 18. $.ajax({ url: 'http://www.xxx.com/api', type: 'POST', success: function(json){ /* do something */ }, error: function(msg){ /* get an error */ } })
  • 20. try{ setTimeout(function(){ throw new Error(':(') }, 0) }catch(e){ alert('get an error'); }
  • 22.
  • 26. 1、jQuery 1.7 版本中新增的 2、jQuery.Callbacks() 函数返回的对象 3、对象对管理回调列表提供了强⼤大的⽅方式 4、能够增加、删除、触发、禁⽤用回调函数 5、⽀支持不同的参数来控制回调执⾏行
  • 27.
  • 28.
  • 29.
  • 33. API
  • 34.
  • 35. var def = jQuery.Deferred(); def.done(function(){ console.warn('done'); }); def.fail(function(){ console.warn('fail'); }); console.warn('def.state() ==>', def.state()); def.reject(); console.warn('def.state() ==>', def.state()); var def = jQuery.Deferred(); def.then(function(){ console.warn('done'); }, function(){ console.warn('fail'); }); console.warn('def.state() ==>', def.state()); def.reject(); console.warn('def.state() ==>', def.state());
  • 37. deferred.then(fnDone[, fnFail[, fnPro]]) 分别调用deferred的 .done(), .fail(), .progress() 添加相应回调函数 return this start end version : 1.5.x/1.6.x/1.7.x 创建新Deferred对象 (newDefer) 分别调用deferred的 .done(), .fail(), .progress() 添加相应回调函数 return newDefer.promise() start end version : 1.8.x+ 职责: 1、执⾏行回掉函数 2、改变新的Deferred对象的状态 3、返回新的Deferred对象
  • 38. deferred.then/pipe 分别调用deferred的 .done(), .fail(), .progress() 添加相应回调函数 return this start end version : 1.5.x/1.6.x/1.7.x then 创建新Deferred 对象 (newDefer) 分别调用deferred的 .done(), .fail(), .progress() 添加相应回调函数 return newDefer.promise() start end version : 1.6.x/1.7.x pipe 创建新Deferred 对象 (newDefer) 分别调用deferred的 .done(), .fail(), .progress() 添加相应回调函数 return newDefer.promise() start end version : 1.8.x+ then
  • 39.
  • 40. d1 done function fail function state “pending” … … doneList Array failList Array doneList 0 changeState 1 failList.disable 2 progress.lock donList和failList实际上不是d1的属性,只是一个局部变量, 为了演示方便,加入到d1
  • 41. d1 done function fail function state “pending” … … doneList Array failList Array doneList 0 changeState 1 failList.disable 2 progress.lock 3 function doneList 0 changeState 1 doneList.disable 2 progress.lock d2 done function fail function then function … … doneList Array failList Array f1 f2 f3 failList 0 changeState 1 failList.disable 2 progress.lock
  • 42. d1 done function then function state “pending” … … doneList Array failList Array doneList 0 changeState 1 failList.disable 2 progress.lock 3 function doneList 0 changeState 1 doneList.disable 2 progress.lock d2 done function fail function then function … … doneList Array failList Array f1 f2 f3 failList 0 changeState 1 failList.disable 2 progress.lock start call fn & get result (returned) isPromise (returned) end returned.promise() .then(…) newDefer[resolve With|rejectWith| progressWith] Y N
  • 43. d1 done function fail function then function … … doneList Array failList Array doneList 0 changeState 1 failList.disable 2 progress.lock 3 function doneList 0 changeState 1 doneList.disable 2 progress.lock 3 function d2 done function fail function then function … … doneList Array failList Array f1 f2 f3 failList 0 changeState 1 failList.disable 2 progress.lock 3 function
  • 44. d1 done function then function state “resolved” … … doneList Array failList Array doneList 0 changeState 1 failList.disable 2 progress.lock 3 function doneList 0 changeState 1 doneList.disable 2 progress.lock 3 function d2 done function fail function then function … … doneList Array failList Array f1 f2 f3 failList 0 changeState 1 failList.disable 2 progress.lock 3 function isPromise(returned = d) == true d.then(d2.resolve, d2.reject) d2.reject() // TODO …. :)
  • 45. d1 done function fail function then function … … doneList Array failList Array failList 0 changeState 1 doneList.disable 2 progress.lock 3 undefined doneList 0 changeState 1 doneList.disable 2 progress.lock 3 function d2 done function fail function then function … … doneList Array failList Array f1 f2 f3 faiList 0 changeState 1 failList.disable 2 progress.lock 3 function returned = fnFail && returned returned == false d2.rejectWith()                 var deferred = $.Deferred();                 deferred.then(function(res){                     console.warn('ok 1');                 },function(err){                     console.warn('err 1');                 })                 .then(function(res){                     console.warn('ok 2');                 },function(err){                     console.warn('err 2');                 })                 .then(function(res){                     console.warn('ok 3');                 },function(err){                     console.warn('err 3');                 });          deferred.reject(); p(deferred)
  • 47.
  • 49. 顺序 / 值 // then var def = $.Deferred(); def.then(     function(val){ console.warn('done +1 ==>', val); return val + 1 } ).then(     function(val){ console.warn('done +2 ==>', val); return val + 2 } ).then(     function(val){ console.warn('done +3 ==>', val); return val + 3 } ) def.resolve(1) // done var def = $.Deferred(); def.done(     function(val){ console.warn('done +1 ==>', val); return val + 1 } ).done(     function(val){ console.warn('done +2 ==>', val); return val + 2 } ).done(     function(val){ console.warn('done +3 ==>', val); return val + 3 } ) def.resolve(1) // then async var def = $.Deferred(); def.then( // d1
  • 56.
  • 57. use // no-deferred object var obj = {   a:1,   b:2 } function func1(obj){   console.warn(obj) } function func2(obj){   console.warn(obj) } func1(obj); func2(obj); // deferred object // deferred object var def1 = $.Deferred(); var def2 = $.Deferred(); function func1(obj){   console.warn(obj) } function func2(obj){   console.warn(obj) }