SlideShare a Scribd company logo
1 of 17
Promises in JavaScript
    with jQuery
     BrisJs Meetup - July 2011
Futures and Promises
•   Futures is the concept behind simplifying the
    management of asynchronous data or
    computations with chainable callbacks.

•   Futures is the concept, promises and deferreds are
    the implementations of this concept.

•   Becoming popular because of implementations by
    jQuery (1.5) Dojo (0.9).

•   Goal - simplify callback management with benefits!
JavaScript
         implementations
•   jQuery - http://api.jquery.com/category/deferred-
    object

•   Dojo - http://dojotoolkit.org/reference-guide/dojo/
    Deferred.html

•   FuturesJS - http://coolaj86.info/futures/

•   Note: Futures are not JavaScript specific.
    http://en.wikipedia.org/wiki/Futures_and_promisesFutures_and_promises
Why is this cool?
• Because you attach success or fail callbacks
  instantly to the returned result!
• Instead of passing success and error
  callbacks to the computation.
• You could then pass the result around to
  other code to register their own success
  or fail callbacks.
No really, WTF is this
      promises stuff.
•   A typical futures pattern could look like:
    when(task1, task2) -> then() or fail() where task1 and task2
    are deferreds (stuff that resolves/completes later).

•   The point of when() is allowing multiple promises to
    complete before calling the callbacks cued for then() or fail()
    are called.

•   You can also do task1 -> then() or fail()

•   “then” is synonymous with “success”.

•   Important! Deferreds and Promises are not interchangeable
    terms. Why?
What are Deferreds

• Deferreds are implementations of futures
  that use promises (internally) to determine
  the state (resolved, un-resolved)of the
  result in a read-only fashion!
Deferreds

•   Deferreds give you (as the author) control of
    setting the state of the underlying promise, what
    callbacks are fired off and and when.

•   When using deferreds, you should only ever return
    the (read only) promise object of the deferred,
    never the deferred itself.
Why is a deferreds
   promise read only?

• Because otherwise, external code could set
  the the state of the internal promise (e.g. to
  resolved when it was actually unresolved).
Ok, so what are
        promises then?
•   Each deferred has a promise which is read only to the
    outside world and only manipulated by the deferred
    itself.

•   Promises have state:
     - unresolved,
     - resolved, or
     - failed.

•   The promise object allows code to access the state of
    the promise and to append callbacks and errbacks but
    not to affect the state of the promise itself.
So how do I use
         deferreds?
• Deferreds enable you to immediately start
  chaining success and error methods to the
  deferred object without waiting for the
  computation or request to complete.
• If when callbacks methods are attached the
  request or computation is done, the
  method(s) will be executed straight away. If
  not, it will get cued up and called later.
Deferred Resources

•   http://developer.yahoo.com/yui/theater/video.php?
    v=crockonjs-3

•   http://addyosmani.com/blog/digging-into-deferreds-1/

•   http://www.erichynds.com/jquery/using-deferreds-in-jquery/

•   http://msdn.microsoft.com/en-us/scriptjunkie/gg723713.aspx
jQuery and Deferreds
       AJAX
•   jQuery introduced deferreds in 1.5 with the
    rewrite of the ajax module.

•   The ajax module returns the underlying promise of
    a deferred allowing you to chain callbacks for
    success(), error() onto the jqXHR object returned.

•   jQuery adds more than just then() and fail() to it’s
    deferreds.
jQuery and Deferreds
       AJAX
•   This was awesome for two reasons:

    •   Made for more readable code

    •   Allowed multiple callbacks for the one Ajax
        request easy

•   Note: Passing around promises may not always be
    the best way for other parts of your app to be
    notified about Ajax data events.
Deferreds in
          jQuery 1.6
• deferred.always() (like complete for the
  ajax module),
• deferred.pipe() which is a way of filtering or
  chaining deferreds, and
• promise() which is an easy way of
  dynamically generating a promise object
  outside of a deferred implementation.
Practical example


• Handlebars.js remote template render
  using jQuery ajax promise
• https://gist.github.com/1064084
The main problems Deferreds
     helps us solve now


• Multiple ajax calls, then(...)
• Easy caching of ajax responses
• Sequential animations - jQuery 1.6
Thanks!


• Ryan Blunden
  ryan.blunden@gmail.com
  @ryan_blunden

More Related Content

What's hot

Improving The Quality of Existing Software
Improving The Quality of Existing SoftwareImproving The Quality of Existing Software
Improving The Quality of Existing SoftwareSteven Smith
 
Improving the Quality of Existing Software
Improving the Quality of Existing SoftwareImproving the Quality of Existing Software
Improving the Quality of Existing SoftwareSteven Smith
 
Test Driven Development in AEM/CQ5
Test Driven Development in AEM/CQ5Test Driven Development in AEM/CQ5
Test Driven Development in AEM/CQ5rtpaem
 
Front-End Modernization for Mortals
Front-End Modernization for MortalsFront-End Modernization for Mortals
Front-End Modernization for Mortalscgack
 
Breaking Dependencies to Allow Unit Testing - DevIntersection Spring 2016
Breaking Dependencies to Allow Unit Testing - DevIntersection Spring 2016Breaking Dependencies to Allow Unit Testing - DevIntersection Spring 2016
Breaking Dependencies to Allow Unit Testing - DevIntersection Spring 2016Steven Smith
 
Improving the Quality of Existing Software - DevIntersection April 2016
Improving the Quality of Existing Software - DevIntersection April 2016Improving the Quality of Existing Software - DevIntersection April 2016
Improving the Quality of Existing Software - DevIntersection April 2016Steven Smith
 
No code to lighting component developer dreamforce 2016
No code to lighting component developer dreamforce 2016No code to lighting component developer dreamforce 2016
No code to lighting component developer dreamforce 2016Kerry Townsend
 
Web based automation testing on Node.js environment
Web based automation testing on Node.js environmentWeb based automation testing on Node.js environment
Web based automation testing on Node.js environmentYu-Lin Huang
 
Bdd with Cucumber and Mocha
Bdd with Cucumber and MochaBdd with Cucumber and Mocha
Bdd with Cucumber and MochaAtish Narlawar
 
Revamped Image Upload: Whys and Hows - Flavio Percoco - OpenStack Day Israel ...
Revamped Image Upload: Whys and Hows - Flavio Percoco - OpenStack Day Israel ...Revamped Image Upload: Whys and Hows - Flavio Percoco - OpenStack Day Israel ...
Revamped Image Upload: Whys and Hows - Flavio Percoco - OpenStack Day Israel ...Cloud Native Day Tel Aviv
 
Automated Acceptance Tests in .NET
Automated Acceptance Tests in .NETAutomated Acceptance Tests in .NET
Automated Acceptance Tests in .NETWyn B. Van Devanter
 
Breaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit TestingBreaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit TestingSteven Smith
 
Test Driven Development in CQ5/AEM
Test Driven Development in CQ5/AEMTest Driven Development in CQ5/AEM
Test Driven Development in CQ5/AEMSagar Sane
 
Selenium + Specflow
Selenium + SpecflowSelenium + Specflow
Selenium + Specflowcromwellryan
 
Slideshare - Magento Imagine - Do You Queue
Slideshare - Magento Imagine - Do You QueueSlideshare - Magento Imagine - Do You Queue
Slideshare - Magento Imagine - Do You Queue10n Software, LLC
 
Making cross browser tests beautiful
Making cross browser tests beautifulMaking cross browser tests beautiful
Making cross browser tests beautifulMeaghan Lewis
 
Common design principles and design patterns in automation testing
Common design principles and design patterns in automation testingCommon design principles and design patterns in automation testing
Common design principles and design patterns in automation testingKMS Technology
 
learn mvc project in 7 day
learn mvc project in 7 daylearn mvc project in 7 day
learn mvc project in 7 dayQuach Long
 

What's hot (20)

Improving The Quality of Existing Software
Improving The Quality of Existing SoftwareImproving The Quality of Existing Software
Improving The Quality of Existing Software
 
Improving the Quality of Existing Software
Improving the Quality of Existing SoftwareImproving the Quality of Existing Software
Improving the Quality of Existing Software
 
Test Driven Development in AEM/CQ5
Test Driven Development in AEM/CQ5Test Driven Development in AEM/CQ5
Test Driven Development in AEM/CQ5
 
Front-End Modernization for Mortals
Front-End Modernization for MortalsFront-End Modernization for Mortals
Front-End Modernization for Mortals
 
Breaking Dependencies to Allow Unit Testing - DevIntersection Spring 2016
Breaking Dependencies to Allow Unit Testing - DevIntersection Spring 2016Breaking Dependencies to Allow Unit Testing - DevIntersection Spring 2016
Breaking Dependencies to Allow Unit Testing - DevIntersection Spring 2016
 
Improving the Quality of Existing Software - DevIntersection April 2016
Improving the Quality of Existing Software - DevIntersection April 2016Improving the Quality of Existing Software - DevIntersection April 2016
Improving the Quality of Existing Software - DevIntersection April 2016
 
No code to lighting component developer dreamforce 2016
No code to lighting component developer dreamforce 2016No code to lighting component developer dreamforce 2016
No code to lighting component developer dreamforce 2016
 
Web based automation testing on Node.js environment
Web based automation testing on Node.js environmentWeb based automation testing on Node.js environment
Web based automation testing on Node.js environment
 
Bdd with Cucumber and Mocha
Bdd with Cucumber and MochaBdd with Cucumber and Mocha
Bdd with Cucumber and Mocha
 
Revamped Image Upload: Whys and Hows - Flavio Percoco - OpenStack Day Israel ...
Revamped Image Upload: Whys and Hows - Flavio Percoco - OpenStack Day Israel ...Revamped Image Upload: Whys and Hows - Flavio Percoco - OpenStack Day Israel ...
Revamped Image Upload: Whys and Hows - Flavio Percoco - OpenStack Day Israel ...
 
Agile Testing
Agile TestingAgile Testing
Agile Testing
 
Automated Acceptance Tests in .NET
Automated Acceptance Tests in .NETAutomated Acceptance Tests in .NET
Automated Acceptance Tests in .NET
 
Breaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit TestingBreaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit Testing
 
Test Driven Development in CQ5/AEM
Test Driven Development in CQ5/AEMTest Driven Development in CQ5/AEM
Test Driven Development in CQ5/AEM
 
Selenium + Specflow
Selenium + SpecflowSelenium + Specflow
Selenium + Specflow
 
Slideshare - Magento Imagine - Do You Queue
Slideshare - Magento Imagine - Do You QueueSlideshare - Magento Imagine - Do You Queue
Slideshare - Magento Imagine - Do You Queue
 
Making cross browser tests beautiful
Making cross browser tests beautifulMaking cross browser tests beautiful
Making cross browser tests beautiful
 
React introduction
React introductionReact introduction
React introduction
 
Common design principles and design patterns in automation testing
Common design principles and design patterns in automation testingCommon design principles and design patterns in automation testing
Common design principles and design patterns in automation testing
 
learn mvc project in 7 day
learn mvc project in 7 daylearn mvc project in 7 day
learn mvc project in 7 day
 

Similar to Promises in JavaScript with jQuery

Async discussion 9_29_15
Async discussion 9_29_15Async discussion 9_29_15
Async discussion 9_29_15Cheryl Yaeger
 
Improving the Design of Existing Software
Improving the Design of Existing SoftwareImproving the Design of Existing Software
Improving the Design of Existing SoftwareSteven Smith
 
O365 Developer Bootcamp NJ 2018 - Material
O365 Developer Bootcamp NJ 2018 - MaterialO365 Developer Bootcamp NJ 2018 - Material
O365 Developer Bootcamp NJ 2018 - MaterialThomas Daly
 
OpenUI5 Conf 2019: Promise Chaining - Create UI applications with Flexible, M...
OpenUI5 Conf 2019: Promise Chaining - Create UI applications with Flexible, M...OpenUI5 Conf 2019: Promise Chaining - Create UI applications with Flexible, M...
OpenUI5 Conf 2019: Promise Chaining - Create UI applications with Flexible, M...Shailendra Rai
 
Avoiding callback hell with promises
Avoiding callback hell with promisesAvoiding callback hell with promises
Avoiding callback hell with promisesTorontoNodeJS
 
Advanced Web Technology.pptx
Advanced Web Technology.pptxAdvanced Web Technology.pptx
Advanced Web Technology.pptxssuser35fdf2
 
III - Better angularjs
III - Better angularjsIII - Better angularjs
III - Better angularjsWebF
 
Continuous Integration and Testing with Branch Orgs
Continuous Integration and Testing with Branch OrgsContinuous Integration and Testing with Branch Orgs
Continuous Integration and Testing with Branch OrgsSalesforce Developers
 
Top 45 jQuery Interview Questions and Answers | Edureka
Top 45 jQuery Interview Questions and Answers | EdurekaTop 45 jQuery Interview Questions and Answers | Edureka
Top 45 jQuery Interview Questions and Answers | EdurekaEdureka!
 
Introduction to react native with redux
Introduction to react native with reduxIntroduction to react native with redux
Introduction to react native with reduxMike Melusky
 
Apex Trigger Debugging: Solving the Hard Problems
Apex Trigger Debugging: Solving the Hard ProblemsApex Trigger Debugging: Solving the Hard Problems
Apex Trigger Debugging: Solving the Hard ProblemsSalesforce Developers
 
Beyond Fluffy Bunny. How I leveraged WebObjects in my lean startup.
Beyond Fluffy Bunny. How I leveraged WebObjects in my lean startup.Beyond Fluffy Bunny. How I leveraged WebObjects in my lean startup.
Beyond Fluffy Bunny. How I leveraged WebObjects in my lean startup.WO Community
 
jQuery 1.4-1.6 Best new features
jQuery 1.4-1.6 Best new featuresjQuery 1.4-1.6 Best new features
jQuery 1.4-1.6 Best new featuresRyan Blunden
 
Web development basics (Part-4)
Web development basics (Part-4)Web development basics (Part-4)
Web development basics (Part-4)Rajat Pratap Singh
 
Bridging the communication Gap & Continuous Delivery
Bridging the communication Gap & Continuous DeliveryBridging the communication Gap & Continuous Delivery
Bridging the communication Gap & Continuous Deliverymasoodjan
 
Validation for APIs in Laravel 4
Validation for APIs in Laravel 4Validation for APIs in Laravel 4
Validation for APIs in Laravel 4Kirk Bushell
 

Similar to Promises in JavaScript with jQuery (20)

Async discussion 9_29_15
Async discussion 9_29_15Async discussion 9_29_15
Async discussion 9_29_15
 
Improving the Design of Existing Software
Improving the Design of Existing SoftwareImproving the Design of Existing Software
Improving the Design of Existing Software
 
O365 Developer Bootcamp NJ 2018 - Material
O365 Developer Bootcamp NJ 2018 - MaterialO365 Developer Bootcamp NJ 2018 - Material
O365 Developer Bootcamp NJ 2018 - Material
 
OpenUI5 Conf 2019: Promise Chaining - Create UI applications with Flexible, M...
OpenUI5 Conf 2019: Promise Chaining - Create UI applications with Flexible, M...OpenUI5 Conf 2019: Promise Chaining - Create UI applications with Flexible, M...
OpenUI5 Conf 2019: Promise Chaining - Create UI applications with Flexible, M...
 
XPages Mobile, #dd13
XPages Mobile, #dd13XPages Mobile, #dd13
XPages Mobile, #dd13
 
Avoiding callback hell with promises
Avoiding callback hell with promisesAvoiding callback hell with promises
Avoiding callback hell with promises
 
Advanced Web Technology.pptx
Advanced Web Technology.pptxAdvanced Web Technology.pptx
Advanced Web Technology.pptx
 
III - Better angularjs
III - Better angularjsIII - Better angularjs
III - Better angularjs
 
Continuous Integration and Testing with Branch Orgs
Continuous Integration and Testing with Branch OrgsContinuous Integration and Testing with Branch Orgs
Continuous Integration and Testing with Branch Orgs
 
Top 45 jQuery Interview Questions and Answers | Edureka
Top 45 jQuery Interview Questions and Answers | EdurekaTop 45 jQuery Interview Questions and Answers | Edureka
Top 45 jQuery Interview Questions and Answers | Edureka
 
Introduction to react native with redux
Introduction to react native with reduxIntroduction to react native with redux
Introduction to react native with redux
 
Apex Trigger Debugging: Solving the Hard Problems
Apex Trigger Debugging: Solving the Hard ProblemsApex Trigger Debugging: Solving the Hard Problems
Apex Trigger Debugging: Solving the Hard Problems
 
Beyond Fluffy Bunny. How I leveraged WebObjects in my lean startup.
Beyond Fluffy Bunny. How I leveraged WebObjects in my lean startup.Beyond Fluffy Bunny. How I leveraged WebObjects in my lean startup.
Beyond Fluffy Bunny. How I leveraged WebObjects in my lean startup.
 
jQuery 1.4-1.6 Best new features
jQuery 1.4-1.6 Best new featuresjQuery 1.4-1.6 Best new features
jQuery 1.4-1.6 Best new features
 
tut0000021-hevery
tut0000021-heverytut0000021-hevery
tut0000021-hevery
 
tut0000021-hevery
tut0000021-heverytut0000021-hevery
tut0000021-hevery
 
Web development basics (Part-4)
Web development basics (Part-4)Web development basics (Part-4)
Web development basics (Part-4)
 
Bridging the communication Gap & Continuous Delivery
Bridging the communication Gap & Continuous DeliveryBridging the communication Gap & Continuous Delivery
Bridging the communication Gap & Continuous Delivery
 
Java 9, JShell, and Modularity
Java 9, JShell, and ModularityJava 9, JShell, and Modularity
Java 9, JShell, and Modularity
 
Validation for APIs in Laravel 4
Validation for APIs in Laravel 4Validation for APIs in Laravel 4
Validation for APIs in Laravel 4
 

Recently uploaded

Science 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxScience 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxMaryGraceBautista27
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Celine George
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfMr Bounab Samir
 
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYKayeClaireEstoconing
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Celine George
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxCarlos105
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfphamnguyenenglishnb
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfTechSoup
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...Nguyen Thanh Tu Collection
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxHumphrey A Beña
 
Q4 English4 Week3 PPT Melcnmg-based.pptx
Q4 English4 Week3 PPT Melcnmg-based.pptxQ4 English4 Week3 PPT Melcnmg-based.pptx
Q4 English4 Week3 PPT Melcnmg-based.pptxnelietumpap1
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...Postal Advocate Inc.
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxChelloAnnAsuncion2
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONHumphrey A Beña
 

Recently uploaded (20)

Science 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxScience 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptx
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptxYOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
 
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
 
Q4 English4 Week3 PPT Melcnmg-based.pptx
Q4 English4 Week3 PPT Melcnmg-based.pptxQ4 English4 Week3 PPT Melcnmg-based.pptx
Q4 English4 Week3 PPT Melcnmg-based.pptx
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
 

Promises in JavaScript with jQuery

  • 1. Promises in JavaScript with jQuery BrisJs Meetup - July 2011
  • 2. Futures and Promises • Futures is the concept behind simplifying the management of asynchronous data or computations with chainable callbacks. • Futures is the concept, promises and deferreds are the implementations of this concept. • Becoming popular because of implementations by jQuery (1.5) Dojo (0.9). • Goal - simplify callback management with benefits!
  • 3. JavaScript implementations • jQuery - http://api.jquery.com/category/deferred- object • Dojo - http://dojotoolkit.org/reference-guide/dojo/ Deferred.html • FuturesJS - http://coolaj86.info/futures/ • Note: Futures are not JavaScript specific. http://en.wikipedia.org/wiki/Futures_and_promisesFutures_and_promises
  • 4. Why is this cool? • Because you attach success or fail callbacks instantly to the returned result! • Instead of passing success and error callbacks to the computation. • You could then pass the result around to other code to register their own success or fail callbacks.
  • 5. No really, WTF is this promises stuff. • A typical futures pattern could look like: when(task1, task2) -> then() or fail() where task1 and task2 are deferreds (stuff that resolves/completes later). • The point of when() is allowing multiple promises to complete before calling the callbacks cued for then() or fail() are called. • You can also do task1 -> then() or fail() • “then” is synonymous with “success”. • Important! Deferreds and Promises are not interchangeable terms. Why?
  • 6. What are Deferreds • Deferreds are implementations of futures that use promises (internally) to determine the state (resolved, un-resolved)of the result in a read-only fashion!
  • 7. Deferreds • Deferreds give you (as the author) control of setting the state of the underlying promise, what callbacks are fired off and and when. • When using deferreds, you should only ever return the (read only) promise object of the deferred, never the deferred itself.
  • 8. Why is a deferreds promise read only? • Because otherwise, external code could set the the state of the internal promise (e.g. to resolved when it was actually unresolved).
  • 9. Ok, so what are promises then? • Each deferred has a promise which is read only to the outside world and only manipulated by the deferred itself. • Promises have state: - unresolved, - resolved, or - failed. • The promise object allows code to access the state of the promise and to append callbacks and errbacks but not to affect the state of the promise itself.
  • 10. So how do I use deferreds? • Deferreds enable you to immediately start chaining success and error methods to the deferred object without waiting for the computation or request to complete. • If when callbacks methods are attached the request or computation is done, the method(s) will be executed straight away. If not, it will get cued up and called later.
  • 11. Deferred Resources • http://developer.yahoo.com/yui/theater/video.php? v=crockonjs-3 • http://addyosmani.com/blog/digging-into-deferreds-1/ • http://www.erichynds.com/jquery/using-deferreds-in-jquery/ • http://msdn.microsoft.com/en-us/scriptjunkie/gg723713.aspx
  • 12. jQuery and Deferreds AJAX • jQuery introduced deferreds in 1.5 with the rewrite of the ajax module. • The ajax module returns the underlying promise of a deferred allowing you to chain callbacks for success(), error() onto the jqXHR object returned. • jQuery adds more than just then() and fail() to it’s deferreds.
  • 13. jQuery and Deferreds AJAX • This was awesome for two reasons: • Made for more readable code • Allowed multiple callbacks for the one Ajax request easy • Note: Passing around promises may not always be the best way for other parts of your app to be notified about Ajax data events.
  • 14. Deferreds in jQuery 1.6 • deferred.always() (like complete for the ajax module), • deferred.pipe() which is a way of filtering or chaining deferreds, and • promise() which is an easy way of dynamically generating a promise object outside of a deferred implementation.
  • 15. Practical example • Handlebars.js remote template render using jQuery ajax promise • https://gist.github.com/1064084
  • 16. The main problems Deferreds helps us solve now • Multiple ajax calls, then(...) • Easy caching of ajax responses • Sequential animations - jQuery 1.6
  • 17. Thanks! • Ryan Blunden ryan.blunden@gmail.com @ryan_blunden

Editor's Notes

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n