SlideShare a Scribd company logo
1 of 51
Download to read offline
PROMISESTHE UNSUNG HEROES OF ASYNC IN
JAVASCRIPT
DEAN RADCLIFFE • OK GROW! •
@DEANIUSDEV
A SPORTING BET
"I BET YOU $20 THE REDS
WON'T BEAT THE CUBS
THIS SEASON..."
TWO PROMISES
➢ Begin Season
then Cubs Lose
then Season Ends
↩ I Pay You
➢ Begin Season
then Season Ends
↩ You Pay Me
TWO PROMISES
➢ Begin Season
then Cubs Lose
// ^ What if we made the bet after a loss ?
then Season Ends
↩ I Pay You
➢ Begin Season
then Season Ends
↩ You Pay Me
PROMISES: EVENTS, AT ANY TIME
A Promise represents a point in time which is:
▸ ASAP, if something has already happened
▸ ASAP the moment it happens
PROMISES: VALUES, AT ANY TIME
A Promise provides access to a value whether:
▸ It is already known
▸ It is being computed in this turn of the Event Loop
▸ It may be un-knowable (maybe use a TimeOut)
PROMISES: ONE OR MORE CONDITIONS & ACTIONS
A Promise can represent an entire chain of events,
with branching possibilities.
var firstStep = new Promise()
var allSteps = firstStep
.then(isReady => isReady || makeReady)
.then(lastStep)
Promise.await(allSteps)
OUR BET - MAKE IT SO
➢ let ourBet = BeginSeason()
.then(Promise.race(CubsLoseToReds(), SeasonEnds()))
.then(cubsLose => cubsLose ? iPayYou : youPayMe)
//.then(iPayYou, youPayMe)
▸ CubsLoseToReds and SeasonEnds return Promises
▸ CubsLose should return truthy (such as the score),
▸ SeasonEnds should return falsy, or throw or reject
UNSUNG HEROES OF ASYNC
▸ Standard, explicit contract of behavior
▸ A promise can resolve or reject
▸ Its state may change 1x from pending to fulfilled
▸ p.then(youPayMe, iPayYou)
▸ Or: p.then((value)=>{})
.catch((err)=>{})
BACK ON THE CHAIN GANG
Each step in a .then chain:
RETURNS A CUMULATIVE PROMISE FOR ALL BEFORE
➢ let chain = promise1
.then(promise2)
.then(action1)
BACK ON THE CHAIN GANG
Each step in a .then chain may:
RETURN A VALUE / RETURN A PROMISE FOR A NEW VALUE
➢ BeginSeasonLossless
.then(CubsLoseToReds) // <-- a Promise
.then(iPayYou)
BACK ON THE CHAIN GANG
Each step in a .then chain may:
RAISE AN EXCEPTION / RETURN REJECTED PROMISE
➢ BeginSeasonLossless
.then(Promise.race(CubsLoseToReds,TimeOutAtSeasonEnd))
.then(iPayYou)
.catch(youPayMe)
EXCEPTIONS
▸ An uncaught exception in a .then is OK!
▸ A catch at the end can handle errors for the whole chain
COMIC RELIEF
CAT PICTURE
QUESTION: HOW DO THESE EVENTS BEHAVE ?
If you add an event listener after an event has happened,
does it make a sound ?
document.addEventListener("DOMContentLoaded")
// vs.
$(document).ready
// vs.
$(document).on("ready")
QUESTION: HOW DO THESE EVENTS BEHAVE ?
If you add an event listener after an event has happened,
does it make a sound ?
document.addEventListener("DOMContentLoaded")
// vs.
$(document).ready // <<-- only this one - like a Promise
// vs.
$(document).on("ready")
PROVIDED ITS LOADED, 1
➢ DomContentLoadedPromise.then(function () {
console.log('Im ready')
});
↩ Promise {[[PromiseStatus]]: "resolved"}
-----
Im ready
PROVIDED ITS LOADED, 2
➢ DomContentLoadedPromise.then(function () {
console.log('Im ready')
});
↩ Promise {[[PromiseStatus]]: "pending"}
-----
PROVIDED ITS LOADED, 2..
➢ DomContentLoadedPromise.then(function () {
console.log('Im ready')
});
↩ Promise {[[PromiseStatus]]: "pending"}
-----
...
PROVIDED ITS LOADED, 3
➢ DomContentLoadedPromise.then(function () {
console.log('Im ready')
});
↩ Promise {[[PromiseStatus]]: "pending"}
-----
...
_____
Im ready
WHAT'S WRONG WITH CALLBACKS ?
Implicit, not formalized standard of behavior:
1. Function that takes 2 arguments
▸ first argument is an error
▸ second argument is the result
▸ Never pass both
▸ error should be instanceof Error
WHAT'S WRONG WITH CALLBACKS ?
Implicit, not formalized standard of behavior (cont.)
1. Must never execute on the same tick of the event loop
2. Must be passed as last argument to function
3. Return value is ignored
4. Must not throw / must pass resulting errors
5. Must never be called more than once
WHAT'S WRONG WITH CALLBACKS ?
▸ Burdensome to check & propogate errors correctly
function doAsyncStuff (cb) {
try {
doStuff1(function(err, value) {
if (err) return cb(err);
try {
doStuff2(value, function(err, value2) {
if (err) return cb(err);
cb(null, value2);
});
} catch (e) {
cb(e);
}
})
} catch (e) {
cb(e);
}
}
WHAT'S RIGHT WITH PROMISES ?
BEAUTIFUL TO CHECK ERRORS, EXCEPTION OR ASYNC!
// Promises FTW !!
function doAsyncStuff () {
return doStuff1()
.then(doStuff2)
.catch(function(err){ /*...*/})
}
THE EVENT LOOP
(AKA TASK
QUEUE)
THE EVENT LOOP (AKA TASK QUEUE)
THE 2 WAYS OF
CODING JS
PROMISES AND REACTIVITY
Keep an upperCase var in sync with
a variable called lowerCase
let lowerCase = new ReactiveVar
let upperCase = new ReactiveVar
PROMISES AND REACTIVITY
Keep an upperCase var in sync with
a variable called lowerCase
let lowerCase = new ReactiveVar
let upperCase = new ReactiveVar
Tracker.autorun(() => {
let x = lowerCase.get()
upperCase.set(x.toUpperCase())
})
PROMISES AND REACTIVITY
Keep an upperCase var in sync with
a variable called lowerCase
lowerCase.set(x).then((x) => {
upperCase.set(x.toUpperCase())
})
PATTERN
RETURNING A PROMISE FROM
A METEOR METHOD
RETURNING A PROMISE FROM A METEOR METHOD
Return a Promise from a Method
Return an Eventual Value from a Method
RETURNING A PROMISE FROM A METEOR METHOD
Return a Promise from a Method
Return an Eventual Value from a Method
Eventually return a value from a Method
RETURNING A PROMISE FROM A METHOD, 1
Meteor.methods({
futureTime() {
return Promise.await(
);
}
})
RETURNING A PROMISE FROM A METHOD, 2
Meteor.methods({
futureTime() {
return Promise.await(new Promise((resolve) => {
//some callback code which should call 'resolve'
}));
}
})
RETURNING A PROMISE FROM A METHOD, 3
Meteor.methods({
futureTime() {
return Promise.await(new Promise((resolve) => {
setTimeout(() => {
console.log("its the future now")
resolve(new Date())
}, 5000)
}));
}
})
RETURNING A PROMISE FROM A METHOD, 4
Meteor.methods({
futureTime() {
let actions = new Promise((resolve) =>
setTimeout(()=> resolve(new Date), 5000))
.then(logAndReturn)
.catch(logAndReturn);
return Promise.await(actions);
}
})
ASYNC SHEEP
CALLING A METHOD
Meteor.promise("futureTime")
.then(log)
CALLING A METHOD, NOW AND LATER
➢ Promise.resolve(new Date)
.then(log)
.then(() => Meteor.promise("futureTime"))
.then(log)
---
Fri Sep 18 2015 22:11:26 GMT-0500 (CDT)
↩ Promise {[[PromiseStatus]]: "pending"}
---
Fri Sep 18 2015 22:11:31 GMT-0500 (CDT)
CALLING A METHOD, FUNNILY
Promise.resolve(new Date)
.then(log)
.then(() => "futureTime")
.then(Meteor.promise)
.then(log)
---
Fri Sep 18 2015 22:11:46 GMT-0500 (CDT)
↩ Promise {[[PromiseStatus]]: "pending",
---
Fri Sep 18 2015 22:11:51 GMT-0500 (CDT)
var ComicReliefCatPicture; // TODO fill in
PROMISES AND REACTIVITY
okgrow:promise
A promise's resolution can invalidate a
computation ?
Awwwwwww yeah !
DEFINE A HELPER AROUND A PROMISE
<template name="example1Demo">
<input id="arg1" value="foo"/>
<input id="arg2" value="bar"/>
<textarea>
{{meteorPromise "addWithSleep" "arg1" "arg2"}}
</textarea>
</template>
RETURN A PROMISE FROM A HELPER
// {{meteorPromise "addWithSleep" "arg1" "arg2"}}
Template.example1Demo.helpers({
meteorPromise: function (methodName, part1, part2) {
var template = Template.instance(),
value1 = template[part1].get(),
value2 = template[part2].get();
// want to - but cant do this !
return Meteor.callPromise(methodName, value1, value2);
}
});
RETURN A PROMISE FROM A HELPER
// {{meteorPromise "addWithSleep" "arg1" "arg2"}}
Template.example1Demo.helpers({
meteorPromise: ReactivePromise(theHelperFunction, {pending: "loading..."})
});
var theHelperFunction = function (methodName, part1, part2) {
var template = Template.instance(),
value1 = template[part1].get(),
value2 = template[part2].get();
return Meteor.callPromise(methodName, value1, value2);
}
TMTOWTDI
CALLBACKS, PROMISES, FIBERS,
REACTIVITY, AND ES6 GENERATORS ARE
ALL WAYS TO BE ASYNC!
(YOU CAN ALWAYS CONVERT)
QUESTIONS ??
PROMISES Я AWESOME
PROMISES Я AWESOME
AND SO ARE YOU!
DEAN RADCLIFFE, OK GROW!
@DEANIUSDEV

More Related Content

Viewers also liked

Viewers also liked (14)

Septiembre
SeptiembreSeptiembre
Septiembre
 
Rec 2002 008
Rec 2002 008Rec 2002 008
Rec 2002 008
 
Fundamentos del pc
Fundamentos del pcFundamentos del pc
Fundamentos del pc
 
Anteproyecto 1
Anteproyecto 1Anteproyecto 1
Anteproyecto 1
 
Longitud de una curva
Longitud de una curvaLongitud de una curva
Longitud de una curva
 
Slideshare
SlideshareSlideshare
Slideshare
 
Delitos informaticos
Delitos informaticosDelitos informaticos
Delitos informaticos
 
Migranodearena presentación
Migranodearena presentaciónMigranodearena presentación
Migranodearena presentación
 
Presentación5
Presentación5Presentación5
Presentación5
 
Equipo1jessica.ivonne.octavio.mari.iyali
Equipo1jessica.ivonne.octavio.mari.iyaliEquipo1jessica.ivonne.octavio.mari.iyali
Equipo1jessica.ivonne.octavio.mari.iyali
 
Jul
JulJul
Jul
 
La revolución energética y la sostenibilidad
La revolución energética y la sostenibilidadLa revolución energética y la sostenibilidad
La revolución energética y la sostenibilidad
 
Mexico
MexicoMexico
Mexico
 
Desconcentración del poder en venezuela
Desconcentración del poder en venezuelaDesconcentración del poder en venezuela
Desconcentración del poder en venezuela
 

Similar to Promises - The Unsung Heroes ofJavaScript

$q and Promises in AngularJS
$q and Promises in AngularJS $q and Promises in AngularJS
$q and Promises in AngularJS a_sharif
 
Callbacks, promises, generators - asynchronous javascript
Callbacks, promises, generators - asynchronous javascriptCallbacks, promises, generators - asynchronous javascript
Callbacks, promises, generators - asynchronous javascriptŁukasz Kużyński
 
AngularJS, More Than Directives !
AngularJS, More Than Directives !AngularJS, More Than Directives !
AngularJS, More Than Directives !Gaurav Behere
 
Difference between promise-chain and promise.all() in Javascript
Difference between promise-chain and promise.all() in JavascriptDifference between promise-chain and promise.all() in Javascript
Difference between promise-chain and promise.all() in JavascriptIdeas2IT Technologies
 
Promises - Asynchronous Control Flow
Promises - Asynchronous Control FlowPromises - Asynchronous Control Flow
Promises - Asynchronous Control FlowHenrique Barcelos
 
Promises are so passé - Tim Perry - Codemotion Milan 2016
Promises are so passé - Tim Perry - Codemotion Milan 2016Promises are so passé - Tim Perry - Codemotion Milan 2016
Promises are so passé - Tim Perry - Codemotion Milan 2016Codemotion
 
New feature of async fakeAsync test in angular
New feature of async fakeAsync test in angularNew feature of async fakeAsync test in angular
New feature of async fakeAsync test in angularJia Li
 
Promises in iOS development
Promises in iOS developmentPromises in iOS development
Promises in iOS developmentRomanPanichkin
 
Promises, promises, and then observables
Promises, promises, and then observablesPromises, promises, and then observables
Promises, promises, and then observablesStefan Charsley
 
4 mishchevskii - testing stage18-
4   mishchevskii - testing stage18-4   mishchevskii - testing stage18-
4 mishchevskii - testing stage18-Ievgenii Katsan
 
A promise is a Promise
A promise is a PromiseA promise is a Promise
A promise is a PromiseMateusz Bryła
 
The Promised Land (in Angular)
The Promised Land (in Angular)The Promised Land (in Angular)
The Promised Land (in Angular)Domenic Denicola
 
Async JavaScript in ES7
Async JavaScript in ES7Async JavaScript in ES7
Async JavaScript in ES7Mike North
 
Promise: async programming hero
Promise: async programming heroPromise: async programming hero
Promise: async programming heroThe Software House
 

Similar to Promises - The Unsung Heroes ofJavaScript (20)

$q and Promises in AngularJS
$q and Promises in AngularJS $q and Promises in AngularJS
$q and Promises in AngularJS
 
Callbacks, promises, generators - asynchronous javascript
Callbacks, promises, generators - asynchronous javascriptCallbacks, promises, generators - asynchronous javascript
Callbacks, promises, generators - asynchronous javascript
 
Promise is a Promise
Promise is a PromisePromise is a Promise
Promise is a Promise
 
AngularJS, More Than Directives !
AngularJS, More Than Directives !AngularJS, More Than Directives !
AngularJS, More Than Directives !
 
Difference between promise-chain and promise.all() in Javascript
Difference between promise-chain and promise.all() in JavascriptDifference between promise-chain and promise.all() in Javascript
Difference between promise-chain and promise.all() in Javascript
 
Promises & limbo
Promises & limboPromises & limbo
Promises & limbo
 
Promises - Asynchronous Control Flow
Promises - Asynchronous Control FlowPromises - Asynchronous Control Flow
Promises - Asynchronous Control Flow
 
Promises are so passé - Tim Perry - Codemotion Milan 2016
Promises are so passé - Tim Perry - Codemotion Milan 2016Promises are so passé - Tim Perry - Codemotion Milan 2016
Promises are so passé - Tim Perry - Codemotion Milan 2016
 
Rxjs ngvikings
Rxjs ngvikingsRxjs ngvikings
Rxjs ngvikings
 
New feature of async fakeAsync test in angular
New feature of async fakeAsync test in angularNew feature of async fakeAsync test in angular
New feature of async fakeAsync test in angular
 
Promises in iOS development
Promises in iOS developmentPromises in iOS development
Promises in iOS development
 
Promises, promises, and then observables
Promises, promises, and then observablesPromises, promises, and then observables
Promises, promises, and then observables
 
Lecture 7
Lecture 7Lecture 7
Lecture 7
 
4 mishchevskii - testing stage18-
4   mishchevskii - testing stage18-4   mishchevskii - testing stage18-
4 mishchevskii - testing stage18-
 
Rxjs swetugg
Rxjs swetuggRxjs swetugg
Rxjs swetugg
 
A promise is a Promise
A promise is a PromiseA promise is a Promise
A promise is a Promise
 
The Promised Land (in Angular)
The Promised Land (in Angular)The Promised Land (in Angular)
The Promised Land (in Angular)
 
Async JavaScript in ES7
Async JavaScript in ES7Async JavaScript in ES7
Async JavaScript in ES7
 
Angular2 rxjs
Angular2 rxjsAngular2 rxjs
Angular2 rxjs
 
Promise: async programming hero
Promise: async programming heroPromise: async programming hero
Promise: async programming hero
 

Recently uploaded

Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceanilsa9823
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 

Recently uploaded (20)

Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 

Promises - The Unsung Heroes ofJavaScript

  • 1. PROMISESTHE UNSUNG HEROES OF ASYNC IN JAVASCRIPT DEAN RADCLIFFE • OK GROW! • @DEANIUSDEV
  • 2. A SPORTING BET "I BET YOU $20 THE REDS WON'T BEAT THE CUBS THIS SEASON..."
  • 3. TWO PROMISES ➢ Begin Season then Cubs Lose then Season Ends ↩ I Pay You ➢ Begin Season then Season Ends ↩ You Pay Me
  • 4. TWO PROMISES ➢ Begin Season then Cubs Lose // ^ What if we made the bet after a loss ? then Season Ends ↩ I Pay You ➢ Begin Season then Season Ends ↩ You Pay Me
  • 5. PROMISES: EVENTS, AT ANY TIME A Promise represents a point in time which is: ▸ ASAP, if something has already happened ▸ ASAP the moment it happens
  • 6. PROMISES: VALUES, AT ANY TIME A Promise provides access to a value whether: ▸ It is already known ▸ It is being computed in this turn of the Event Loop ▸ It may be un-knowable (maybe use a TimeOut)
  • 7. PROMISES: ONE OR MORE CONDITIONS & ACTIONS A Promise can represent an entire chain of events, with branching possibilities. var firstStep = new Promise() var allSteps = firstStep .then(isReady => isReady || makeReady) .then(lastStep) Promise.await(allSteps)
  • 8. OUR BET - MAKE IT SO ➢ let ourBet = BeginSeason() .then(Promise.race(CubsLoseToReds(), SeasonEnds())) .then(cubsLose => cubsLose ? iPayYou : youPayMe) //.then(iPayYou, youPayMe) ▸ CubsLoseToReds and SeasonEnds return Promises ▸ CubsLose should return truthy (such as the score), ▸ SeasonEnds should return falsy, or throw or reject
  • 9. UNSUNG HEROES OF ASYNC ▸ Standard, explicit contract of behavior ▸ A promise can resolve or reject ▸ Its state may change 1x from pending to fulfilled ▸ p.then(youPayMe, iPayYou) ▸ Or: p.then((value)=>{}) .catch((err)=>{})
  • 10. BACK ON THE CHAIN GANG Each step in a .then chain: RETURNS A CUMULATIVE PROMISE FOR ALL BEFORE ➢ let chain = promise1 .then(promise2) .then(action1)
  • 11. BACK ON THE CHAIN GANG Each step in a .then chain may: RETURN A VALUE / RETURN A PROMISE FOR A NEW VALUE ➢ BeginSeasonLossless .then(CubsLoseToReds) // <-- a Promise .then(iPayYou)
  • 12. BACK ON THE CHAIN GANG Each step in a .then chain may: RAISE AN EXCEPTION / RETURN REJECTED PROMISE ➢ BeginSeasonLossless .then(Promise.race(CubsLoseToReds,TimeOutAtSeasonEnd)) .then(iPayYou) .catch(youPayMe)
  • 13. EXCEPTIONS ▸ An uncaught exception in a .then is OK! ▸ A catch at the end can handle errors for the whole chain
  • 15. QUESTION: HOW DO THESE EVENTS BEHAVE ? If you add an event listener after an event has happened, does it make a sound ? document.addEventListener("DOMContentLoaded") // vs. $(document).ready // vs. $(document).on("ready")
  • 16. QUESTION: HOW DO THESE EVENTS BEHAVE ? If you add an event listener after an event has happened, does it make a sound ? document.addEventListener("DOMContentLoaded") // vs. $(document).ready // <<-- only this one - like a Promise // vs. $(document).on("ready")
  • 17. PROVIDED ITS LOADED, 1 ➢ DomContentLoadedPromise.then(function () { console.log('Im ready') }); ↩ Promise {[[PromiseStatus]]: "resolved"} ----- Im ready
  • 18. PROVIDED ITS LOADED, 2 ➢ DomContentLoadedPromise.then(function () { console.log('Im ready') }); ↩ Promise {[[PromiseStatus]]: "pending"} -----
  • 19. PROVIDED ITS LOADED, 2.. ➢ DomContentLoadedPromise.then(function () { console.log('Im ready') }); ↩ Promise {[[PromiseStatus]]: "pending"} ----- ...
  • 20. PROVIDED ITS LOADED, 3 ➢ DomContentLoadedPromise.then(function () { console.log('Im ready') }); ↩ Promise {[[PromiseStatus]]: "pending"} ----- ... _____ Im ready
  • 21. WHAT'S WRONG WITH CALLBACKS ? Implicit, not formalized standard of behavior: 1. Function that takes 2 arguments ▸ first argument is an error ▸ second argument is the result ▸ Never pass both ▸ error should be instanceof Error
  • 22. WHAT'S WRONG WITH CALLBACKS ? Implicit, not formalized standard of behavior (cont.) 1. Must never execute on the same tick of the event loop 2. Must be passed as last argument to function 3. Return value is ignored 4. Must not throw / must pass resulting errors 5. Must never be called more than once
  • 23. WHAT'S WRONG WITH CALLBACKS ? ▸ Burdensome to check & propogate errors correctly function doAsyncStuff (cb) { try { doStuff1(function(err, value) { if (err) return cb(err); try { doStuff2(value, function(err, value2) { if (err) return cb(err); cb(null, value2); }); } catch (e) { cb(e); } }) } catch (e) { cb(e); } }
  • 24. WHAT'S RIGHT WITH PROMISES ? BEAUTIFUL TO CHECK ERRORS, EXCEPTION OR ASYNC! // Promises FTW !! function doAsyncStuff () { return doStuff1() .then(doStuff2) .catch(function(err){ /*...*/}) }
  • 25. THE EVENT LOOP (AKA TASK QUEUE)
  • 26. THE EVENT LOOP (AKA TASK QUEUE)
  • 27. THE 2 WAYS OF CODING JS
  • 28. PROMISES AND REACTIVITY Keep an upperCase var in sync with a variable called lowerCase let lowerCase = new ReactiveVar let upperCase = new ReactiveVar
  • 29. PROMISES AND REACTIVITY Keep an upperCase var in sync with a variable called lowerCase let lowerCase = new ReactiveVar let upperCase = new ReactiveVar Tracker.autorun(() => { let x = lowerCase.get() upperCase.set(x.toUpperCase()) })
  • 30. PROMISES AND REACTIVITY Keep an upperCase var in sync with a variable called lowerCase lowerCase.set(x).then((x) => { upperCase.set(x.toUpperCase()) })
  • 31. PATTERN RETURNING A PROMISE FROM A METEOR METHOD
  • 32. RETURNING A PROMISE FROM A METEOR METHOD Return a Promise from a Method Return an Eventual Value from a Method
  • 33. RETURNING A PROMISE FROM A METEOR METHOD Return a Promise from a Method Return an Eventual Value from a Method Eventually return a value from a Method
  • 34. RETURNING A PROMISE FROM A METHOD, 1 Meteor.methods({ futureTime() { return Promise.await( ); } })
  • 35. RETURNING A PROMISE FROM A METHOD, 2 Meteor.methods({ futureTime() { return Promise.await(new Promise((resolve) => { //some callback code which should call 'resolve' })); } })
  • 36. RETURNING A PROMISE FROM A METHOD, 3 Meteor.methods({ futureTime() { return Promise.await(new Promise((resolve) => { setTimeout(() => { console.log("its the future now") resolve(new Date()) }, 5000) })); } })
  • 37. RETURNING A PROMISE FROM A METHOD, 4 Meteor.methods({ futureTime() { let actions = new Promise((resolve) => setTimeout(()=> resolve(new Date), 5000)) .then(logAndReturn) .catch(logAndReturn); return Promise.await(actions); } })
  • 40. CALLING A METHOD, NOW AND LATER ➢ Promise.resolve(new Date) .then(log) .then(() => Meteor.promise("futureTime")) .then(log) --- Fri Sep 18 2015 22:11:26 GMT-0500 (CDT) ↩ Promise {[[PromiseStatus]]: "pending"} --- Fri Sep 18 2015 22:11:31 GMT-0500 (CDT)
  • 41. CALLING A METHOD, FUNNILY Promise.resolve(new Date) .then(log) .then(() => "futureTime") .then(Meteor.promise) .then(log) --- Fri Sep 18 2015 22:11:46 GMT-0500 (CDT) ↩ Promise {[[PromiseStatus]]: "pending", --- Fri Sep 18 2015 22:11:51 GMT-0500 (CDT)
  • 43. PROMISES AND REACTIVITY okgrow:promise A promise's resolution can invalidate a computation ? Awwwwwww yeah !
  • 44. DEFINE A HELPER AROUND A PROMISE <template name="example1Demo"> <input id="arg1" value="foo"/> <input id="arg2" value="bar"/> <textarea> {{meteorPromise "addWithSleep" "arg1" "arg2"}} </textarea> </template>
  • 45. RETURN A PROMISE FROM A HELPER // {{meteorPromise "addWithSleep" "arg1" "arg2"}} Template.example1Demo.helpers({ meteorPromise: function (methodName, part1, part2) { var template = Template.instance(), value1 = template[part1].get(), value2 = template[part2].get(); // want to - but cant do this ! return Meteor.callPromise(methodName, value1, value2); } });
  • 46. RETURN A PROMISE FROM A HELPER // {{meteorPromise "addWithSleep" "arg1" "arg2"}} Template.example1Demo.helpers({ meteorPromise: ReactivePromise(theHelperFunction, {pending: "loading..."}) }); var theHelperFunction = function (methodName, part1, part2) { var template = Template.instance(), value1 = template[part1].get(), value2 = template[part2].get(); return Meteor.callPromise(methodName, value1, value2); }
  • 47. TMTOWTDI CALLBACKS, PROMISES, FIBERS, REACTIVITY, AND ES6 GENERATORS ARE ALL WAYS TO BE ASYNC! (YOU CAN ALWAYS CONVERT)
  • 50. PROMISES Я AWESOME AND SO ARE YOU!
  • 51. DEAN RADCLIFFE, OK GROW! @DEANIUSDEV