SlideShare a Scribd company logo
1 of 52
Download to read offline
Promises, Promises
Mastering Async in Javascript
with the Promise Pattern
by Christian Lilley
about.me/xml
Thursday, September 19, 13
1st, our Problem...
Do Thing A.
Do Thing B using output of
Thing A.
But Thing A hasn’t returned
yet, & you don’t know when it
will!!!
Thursday, September 19, 13
Then, the *Name*
YMMV. Ignore the name if you need to.
also: ‘Futures’, ‘Deferrables’, et al.
Some of those are misleading...
But still pithier than my ‘Time-
Independent Proxy Objects’
TIPOs!
Better: ‘Timeless Values’, ‘IOUs’
Thursday, September 19, 13
The Nature of JS
Thursday, September 19, 13
Thursday, September 19, 13
The Nature of JS
(Terminology on this stuff varies:
smarter people than me argue about
‘blocking’ vs. ‘non-blocking’, etc.)
FWIW, JS doesn’t have ‘real’
concurrency or coroutines
‘Just’ a Single-Threaded Event Loop
Which actually works really well, once
you understand it.
Hence, Node’s doing pretty well.
Thursday, September 19, 13
The Default Option
So, by default, Async in JS is all
about callbacks.
Callbacks get an otherwise blocking
long-lived function out of the loop.
They’re the exception to sequential,
‘blocking’ execution.
Callbacks don’t return values, they
have *side-effects*
If you miss them, they’re gone forever
Thursday, September 19, 13
Callback Reality
So, callbacks work, but they’re a
pain to compose and think about: tons
of manual control-flow, custom event
systems, caching of process states...
People hate callbacks so much, they
come up with colorful names for what
they make their code look like:
“Callback Hell”, or...
“Callback Spaghetti”, or...
Thursday, September 19, 13
step1(value1,	
  function	
  (output)	
  {
	
  	
  	
  	
  step2(output1,	
  function(output2)	
  {
	
  	
  	
  	
  	
  	
  	
  	
  step3(output2,	
  function(output3)	
  {
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  step4(output3,	
  function(output4)	
  {
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  //	
  Do	
  something	
  with	
  value4,
	
  	
  	
  	
  quick,	
  before	
  it	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  
	
  	
  	
  	
  disappears!!!
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  });
	
  	
  	
  	
  	
  	
  	
  	
  });
	
  	
  	
  	
  });
});
Thursday, September 19, 13
PYRAMID OF
DOOOM!!!!
Thursday, September 19, 13
Doom is bad.
Thursday, September 19, 13
Instead, how
about...
Thursday, September 19, 13
Q.fcall(step1)
.then(step2)
.then(step3)
.then(step4);
Nice! Although, what if we don’t want
to chain everything at once?...
Thursday, September 19, 13
var myPromise = Q.fcall(step1);
// later...
var newPromise = myPromise.then(step2);
// much later...
newPromise.then(step3).then(step4);
// and some other time entirely...
myPromise.then(step5)
Thursday, September 19, 13
Or, Aggregation!
Thursday, September 19, 13
// First, do one thing:
var 1stPromise = Q.fcall(step1);
// After that, do 3 other things
var 2ndPromise = myPromise.then(step2);
var 3rdPromise = myPromise.then(step3);
var 4thPromise = myPromise.then(step4);
// And only after those 3 finish...
Q.all([2ndPromise, 3rdPromise,
4thPromise]).then(step5)
Thursday, September 19, 13
So, what’s going on?
Q.js is a utility library for
generating promises. There are others,
but Q is the gold-standard, and fully
compliant with Promises/A+ spec.
Subset of Q is in Angular: $Q
JQuery has an implementation: avoid
In the past, folks used Async.js,
other utilities, for similar purposes.
Thursday, September 19, 13
But, what’s a
Promise?!?
A promise is something very simple,
but very powerful:
a container that holds a value,
or will hold a value
a time-independent proxy for a
remote/external object
an instance of a class that has
utility methods like .then()
Thursday, September 19, 13
But, what’s a
Promise?!?
A ‘frozen event’ you can learn status
of at any time.
It’s a first-class object, so you
can:
Pass it
Reference it
Chain it
All these things, in ONE PACKAGE
Thursday, September 19, 13
Metaphors:
Thursday, September 19, 13
Mailbox/Loading-Dock
A package containing a new drive is
coming. Will be delivered to this
spot, but not sure when.
var newDriveReady =
orderDrive().then(openBox).then(copyData)
var oldDriveGone =
newDriveReady.then(wipeDrive).then(sellDrive)
var newDriveInstalled =
newDriveReady.then(installDrive)
Q.all([newDriveInstalled,
oldDriveGone]).done(downloadMoreMusic)
Thursday, September 19, 13
Family Messaging
Rather than standing waiting for your
kid at school, & for spouse at work,
make plans & do other stuff.
var kidPromise = kidToSchool();
var childHome =
kidPromise.then(smsReceived).then(pickUpKid);
var foodAvailable = kidPromise.then(goShopping);
var spouseHome =
spouseToWork().then(vmReceived).then(pickUpSpouse);
Q.all([childHome, spouseHome, foodAvailable])
.then(makeDinner).done(eatDinner);
Thursday, September 19, 13
Money
The callback approach to life is that
you get paid for your work in
perishable goods, like food.
You have to preserve or sell it to be
able to store it.
Wouldn’t you rather just get paid in
money, which you can spend, save, or
even take out loans against?
Thursday, September 19, 13
So, yes: it’s very nice syntactic
sugar for composing more readable
interactions, especially with
callback-based applications.
But that’s missing the bigger points:
Persistent Events
Cached Values from I/O operations
Error-Handling
Take async out of controllers,
etc., w/ patterns like Angular’s
Thursday, September 19, 13
Infinitely chainable: Promise methods
return a promise, either transformed
or original.
Aggregation, with .all
Furthermore...
Thursday, September 19, 13
How-To
Thursday, September 19, 13
Consuming
At first, consume promises from Angular's
$HTTP, similar methods that return promises
that you've maybe been ignoring all along.
Inspect the state of a promise with:
promise.inspect()
(returns state & value or reason)
promise.isPending()
promise.isFulfilled()
promise.isRejected()
Thursday, September 19, 13
Consuming
But once you've seen how much easier
life gets when you take maximum
advantage of Promises, you'll want to
not only consume them, but produce
your own...
Thursday, September 19, 13
Producing - Step 1
Start Simple, by wrapping a basic
value or function output in a
Promise, so you can .then() or .all()
Q.fcall(function() {return 10;});
Q.fcall(calculateSomething(data));
These promises will already be
resolved. (They’re not async, right?)
Thursday, September 19, 13
Producing - Step 2
Take callback-producing functions and
turn them easily into promise-producing
functions, especially in Node:
var filePromise =
Q.nfcall(FS.readFile, "foo.txt", "utf-8");
filePromise.done(handler);
(‘nfcall()’ = node function call, but
you can use it elsewhere)
(There’s also nfapply(), of course.)
Thursday, September 19, 13
Producing - Step 3
If you want to assemble your own
promise-generating functions, from-
scratch, and resolve or reject when/
how you wish, you want...
Thursday, September 19, 13
Deferreds
Thursday, September 19, 13
What’s a Deferred?
If a Promise is a container for a
value, then a Deferred is the
custodian of the container, taking
care of it until it grows up & leaves
home.
The promise is a property of the
deferred, which also has special
methods for resolving the promise.
So, re-using the previous example:
Thursday, September 19, 13
var deferred = Q.defer();
FS.readFile("foo.txt", "utf-8",
// callback to `readFile()`
function (error, text) {
if (error) {
deferred.reject(new Error(error));
} else {
deferred.resolve(text);
}
}
);
// returns the promise before the async
function completes
return deferred.promise;
Thursday, September 19, 13
The Promise is a separate
object, to which the
Deferred holds a
reference:
Thursday, September 19, 13
Deferred
for creating,
resolving promises
Promise
User/Consumer
methods live here.
.resolve()
.reject()
.promise
.then()
.done()
.all()
.inspect()
.state
.value
.catch()
.fcall()
etc...
Thursday, September 19, 13
Which can do What?
You can’t change the state of a
Promise directly. Only its Deferred
object can do that.
The Deferred is able to resolve or
reject the Promise. If you don’t have
the Deferred, you’re just a consumer.
Promise is a bit like the compiled
binary, Deferred is the source.
Thursday, September 19, 13
Let’s beat that
mailbox metaphor to
death, shall we?
Thursday, September 19, 13
If the Promise is the
mailbox, then the Deferred:
Is the Postman.
Thursday, September 19, 13
No, not that
one, thank
God...
Thursday, September 19, 13
If the Promise is the
mailbox, then the Deferred:
Is the Postman.
The Postman is the only one who’s
allowed to:
Assign you a new mailbox.
(ie. create a promise)
Put new packages into the
mailbox. (resolve the promise)
Raise the little flag on the
side. (set state of the promise)
Thursday, September 19, 13
Recap:
Thursday, September 19, 13
Promises Get You
Clear, Declarative Control-Flow That
Works Regardless of Time & Place
Persistent Events, Clear Handlers
Parallelism, Aggregation
Caching of Async Values
Excellent Error-Handling
Thursday, September 19, 13
Advanced Patterns
Thursday, September 19, 13
Promises from Other
Libraries
Not all promises are Promises/A+ spec
I’m looking at you, JQuery.
Also, some spec libraries are limited
Wrap any other promise in conversion
methods like Q(jqueryPromise);
Just like wrapping a bare DOM element
in JQuery, so you can use those
methods.
Thursday, September 19, 13
Angular & Promises
Angular shows what you can do when
you start thinking in Promises.
Most async methods return promises.
($resource used to be an exception,
but that’s changing in 1.2)
Thursday, September 19, 13
Angular & Promises
`resolve` property on routes: always
resolved before controller
instantiated, view rendered.
allows controllers, views to be
fully time-agnostic
more modular, reusable, focused
Make use of a *service* (a persistent
singleton) to cache your promises,
perhaps using...
Thursday, September 19, 13
Lazy Promises
Use a simple getter function that
will return a promise if it already
exists (whether resolved yet, or
not), or generate one if needed.
Works well with namespace() for
creating hierarchies on the fly.
Promises/A+ considering standardizing
AMD loaders basically built on them
Thursday, September 19, 13
function getDivision(divisionName) {
if (!divisionObjects[divisionName])
{
divisionObjects[divisionName] =
$http.get(baseUrl + divisionName)
.error(function(data, status) {
console.error('getDivision
failed, error:' + status)
});
} else {
return
divisionObjects[divisionName];
}
}
Thursday, September 19, 13
Notes
Async.JS - Still useful, but promises
are a better overall abstraction,
that can change your whole structure.
AMD/Require.JS is async and is a
version of promises: *lazy* promises.
I lied before: Web Workers are
bringing real concurrency/multi-
threading to JS !!! (IE 10 or better)
But they won’t make callbacks go
away.
Thursday, September 19, 13
Notes
Node is recent enough that they
certainly could have used Promises
instead of callbacks. And servers are
all about I/O. But everybody already
understands callbacks...
Robust, readable error-handling is
another great feature of Promises.
Thursday, September 19, 13
References
John Resig: How Timers Work (Also generally about
the whole JS event-loop)
Trevor Burnham: Flow-Control With Promises
Callbacks are imperative, promises are
functional: Node’s biggest missed opportunity
Domenic: You’re Missing the Point of Promises
Trevor Burnham’s Async Javascript (Book @
PragProg)
Writing Asynchronous Javascript 101 (It should
actually be a ‘301’, and is dated, but good info)
Thursday, September 19, 13

More Related Content

Recently uploaded

SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetHyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetEnjoy Anytime
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxnull - The Open Security Community
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 

Recently uploaded (20)

SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetHyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 

Featured

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by HubspotMarius Sescu
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTExpeed Software
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsPixeldarts
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthThinkNow
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfmarketingartwork
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024Neil Kimberley
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)contently
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024Albert Qian
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsKurio // The Social Media Age(ncy)
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Search Engine Journal
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summarySpeakerHub
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next Tessa Mero
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentLily Ray
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best PracticesVit Horky
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project managementMindGenius
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...RachelPearson36
 

Featured (20)

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPT
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 

Promises, Promises: Mastering Async I/O in Javascript with the Promise Pattern

  • 1. Promises, Promises Mastering Async in Javascript with the Promise Pattern by Christian Lilley about.me/xml Thursday, September 19, 13
  • 2. 1st, our Problem... Do Thing A. Do Thing B using output of Thing A. But Thing A hasn’t returned yet, & you don’t know when it will!!! Thursday, September 19, 13
  • 3. Then, the *Name* YMMV. Ignore the name if you need to. also: ‘Futures’, ‘Deferrables’, et al. Some of those are misleading... But still pithier than my ‘Time- Independent Proxy Objects’ TIPOs! Better: ‘Timeless Values’, ‘IOUs’ Thursday, September 19, 13
  • 4. The Nature of JS Thursday, September 19, 13
  • 6. The Nature of JS (Terminology on this stuff varies: smarter people than me argue about ‘blocking’ vs. ‘non-blocking’, etc.) FWIW, JS doesn’t have ‘real’ concurrency or coroutines ‘Just’ a Single-Threaded Event Loop Which actually works really well, once you understand it. Hence, Node’s doing pretty well. Thursday, September 19, 13
  • 7. The Default Option So, by default, Async in JS is all about callbacks. Callbacks get an otherwise blocking long-lived function out of the loop. They’re the exception to sequential, ‘blocking’ execution. Callbacks don’t return values, they have *side-effects* If you miss them, they’re gone forever Thursday, September 19, 13
  • 8. Callback Reality So, callbacks work, but they’re a pain to compose and think about: tons of manual control-flow, custom event systems, caching of process states... People hate callbacks so much, they come up with colorful names for what they make their code look like: “Callback Hell”, or... “Callback Spaghetti”, or... Thursday, September 19, 13
  • 9. step1(value1,  function  (output)  {        step2(output1,  function(output2)  {                step3(output2,  function(output3)  {                        step4(output3,  function(output4)  {                                //  Do  something  with  value4,        quick,  before  it                                  disappears!!!                        });                });        }); }); Thursday, September 19, 13
  • 11. Doom is bad. Thursday, September 19, 13
  • 13. Q.fcall(step1) .then(step2) .then(step3) .then(step4); Nice! Although, what if we don’t want to chain everything at once?... Thursday, September 19, 13
  • 14. var myPromise = Q.fcall(step1); // later... var newPromise = myPromise.then(step2); // much later... newPromise.then(step3).then(step4); // and some other time entirely... myPromise.then(step5) Thursday, September 19, 13
  • 16. // First, do one thing: var 1stPromise = Q.fcall(step1); // After that, do 3 other things var 2ndPromise = myPromise.then(step2); var 3rdPromise = myPromise.then(step3); var 4thPromise = myPromise.then(step4); // And only after those 3 finish... Q.all([2ndPromise, 3rdPromise, 4thPromise]).then(step5) Thursday, September 19, 13
  • 17. So, what’s going on? Q.js is a utility library for generating promises. There are others, but Q is the gold-standard, and fully compliant with Promises/A+ spec. Subset of Q is in Angular: $Q JQuery has an implementation: avoid In the past, folks used Async.js, other utilities, for similar purposes. Thursday, September 19, 13
  • 18. But, what’s a Promise?!? A promise is something very simple, but very powerful: a container that holds a value, or will hold a value a time-independent proxy for a remote/external object an instance of a class that has utility methods like .then() Thursday, September 19, 13
  • 19. But, what’s a Promise?!? A ‘frozen event’ you can learn status of at any time. It’s a first-class object, so you can: Pass it Reference it Chain it All these things, in ONE PACKAGE Thursday, September 19, 13
  • 21. Mailbox/Loading-Dock A package containing a new drive is coming. Will be delivered to this spot, but not sure when. var newDriveReady = orderDrive().then(openBox).then(copyData) var oldDriveGone = newDriveReady.then(wipeDrive).then(sellDrive) var newDriveInstalled = newDriveReady.then(installDrive) Q.all([newDriveInstalled, oldDriveGone]).done(downloadMoreMusic) Thursday, September 19, 13
  • 22. Family Messaging Rather than standing waiting for your kid at school, & for spouse at work, make plans & do other stuff. var kidPromise = kidToSchool(); var childHome = kidPromise.then(smsReceived).then(pickUpKid); var foodAvailable = kidPromise.then(goShopping); var spouseHome = spouseToWork().then(vmReceived).then(pickUpSpouse); Q.all([childHome, spouseHome, foodAvailable]) .then(makeDinner).done(eatDinner); Thursday, September 19, 13
  • 23. Money The callback approach to life is that you get paid for your work in perishable goods, like food. You have to preserve or sell it to be able to store it. Wouldn’t you rather just get paid in money, which you can spend, save, or even take out loans against? Thursday, September 19, 13
  • 24. So, yes: it’s very nice syntactic sugar for composing more readable interactions, especially with callback-based applications. But that’s missing the bigger points: Persistent Events Cached Values from I/O operations Error-Handling Take async out of controllers, etc., w/ patterns like Angular’s Thursday, September 19, 13
  • 25. Infinitely chainable: Promise methods return a promise, either transformed or original. Aggregation, with .all Furthermore... Thursday, September 19, 13
  • 27. Consuming At first, consume promises from Angular's $HTTP, similar methods that return promises that you've maybe been ignoring all along. Inspect the state of a promise with: promise.inspect() (returns state & value or reason) promise.isPending() promise.isFulfilled() promise.isRejected() Thursday, September 19, 13
  • 28. Consuming But once you've seen how much easier life gets when you take maximum advantage of Promises, you'll want to not only consume them, but produce your own... Thursday, September 19, 13
  • 29. Producing - Step 1 Start Simple, by wrapping a basic value or function output in a Promise, so you can .then() or .all() Q.fcall(function() {return 10;}); Q.fcall(calculateSomething(data)); These promises will already be resolved. (They’re not async, right?) Thursday, September 19, 13
  • 30. Producing - Step 2 Take callback-producing functions and turn them easily into promise-producing functions, especially in Node: var filePromise = Q.nfcall(FS.readFile, "foo.txt", "utf-8"); filePromise.done(handler); (‘nfcall()’ = node function call, but you can use it elsewhere) (There’s also nfapply(), of course.) Thursday, September 19, 13
  • 31. Producing - Step 3 If you want to assemble your own promise-generating functions, from- scratch, and resolve or reject when/ how you wish, you want... Thursday, September 19, 13
  • 33. What’s a Deferred? If a Promise is a container for a value, then a Deferred is the custodian of the container, taking care of it until it grows up & leaves home. The promise is a property of the deferred, which also has special methods for resolving the promise. So, re-using the previous example: Thursday, September 19, 13
  • 34. var deferred = Q.defer(); FS.readFile("foo.txt", "utf-8", // callback to `readFile()` function (error, text) { if (error) { deferred.reject(new Error(error)); } else { deferred.resolve(text); } } ); // returns the promise before the async function completes return deferred.promise; Thursday, September 19, 13
  • 35. The Promise is a separate object, to which the Deferred holds a reference: Thursday, September 19, 13
  • 36. Deferred for creating, resolving promises Promise User/Consumer methods live here. .resolve() .reject() .promise .then() .done() .all() .inspect() .state .value .catch() .fcall() etc... Thursday, September 19, 13
  • 37. Which can do What? You can’t change the state of a Promise directly. Only its Deferred object can do that. The Deferred is able to resolve or reject the Promise. If you don’t have the Deferred, you’re just a consumer. Promise is a bit like the compiled binary, Deferred is the source. Thursday, September 19, 13
  • 38. Let’s beat that mailbox metaphor to death, shall we? Thursday, September 19, 13
  • 39. If the Promise is the mailbox, then the Deferred: Is the Postman. Thursday, September 19, 13
  • 40. No, not that one, thank God... Thursday, September 19, 13
  • 41. If the Promise is the mailbox, then the Deferred: Is the Postman. The Postman is the only one who’s allowed to: Assign you a new mailbox. (ie. create a promise) Put new packages into the mailbox. (resolve the promise) Raise the little flag on the side. (set state of the promise) Thursday, September 19, 13
  • 43. Promises Get You Clear, Declarative Control-Flow That Works Regardless of Time & Place Persistent Events, Clear Handlers Parallelism, Aggregation Caching of Async Values Excellent Error-Handling Thursday, September 19, 13
  • 45. Promises from Other Libraries Not all promises are Promises/A+ spec I’m looking at you, JQuery. Also, some spec libraries are limited Wrap any other promise in conversion methods like Q(jqueryPromise); Just like wrapping a bare DOM element in JQuery, so you can use those methods. Thursday, September 19, 13
  • 46. Angular & Promises Angular shows what you can do when you start thinking in Promises. Most async methods return promises. ($resource used to be an exception, but that’s changing in 1.2) Thursday, September 19, 13
  • 47. Angular & Promises `resolve` property on routes: always resolved before controller instantiated, view rendered. allows controllers, views to be fully time-agnostic more modular, reusable, focused Make use of a *service* (a persistent singleton) to cache your promises, perhaps using... Thursday, September 19, 13
  • 48. Lazy Promises Use a simple getter function that will return a promise if it already exists (whether resolved yet, or not), or generate one if needed. Works well with namespace() for creating hierarchies on the fly. Promises/A+ considering standardizing AMD loaders basically built on them Thursday, September 19, 13
  • 49. function getDivision(divisionName) { if (!divisionObjects[divisionName]) { divisionObjects[divisionName] = $http.get(baseUrl + divisionName) .error(function(data, status) { console.error('getDivision failed, error:' + status) }); } else { return divisionObjects[divisionName]; } } Thursday, September 19, 13
  • 50. Notes Async.JS - Still useful, but promises are a better overall abstraction, that can change your whole structure. AMD/Require.JS is async and is a version of promises: *lazy* promises. I lied before: Web Workers are bringing real concurrency/multi- threading to JS !!! (IE 10 or better) But they won’t make callbacks go away. Thursday, September 19, 13
  • 51. Notes Node is recent enough that they certainly could have used Promises instead of callbacks. And servers are all about I/O. But everybody already understands callbacks... Robust, readable error-handling is another great feature of Promises. Thursday, September 19, 13
  • 52. References John Resig: How Timers Work (Also generally about the whole JS event-loop) Trevor Burnham: Flow-Control With Promises Callbacks are imperative, promises are functional: Node’s biggest missed opportunity Domenic: You’re Missing the Point of Promises Trevor Burnham’s Async Javascript (Book @ PragProg) Writing Asynchronous Javascript 101 (It should actually be a ‘301’, and is dated, but good info) Thursday, September 19, 13