SlideShare une entreprise Scribd logo
1  sur  48
Télécharger pour lire hors ligne
John Newman
@jnewmanux • github.com/jgnewman
rescuecreative@gmail.com
UNDERSTANDING ASYNCHRONOUS
JAVASCRIPT
TallyJS - June 2014
What is asynchronous
programming?
“There are two hard things in
computer science: cache
invalidation, naming things,
and off-by-one errors.
- Unknown
Somebody go to Google and search "define synchronous"
Wikipedia
codewala.net
Our Simple Definition
Parallel computing is a form of computation in which many calculations are carried
out simultaneously, operating on the principle that large problems can often be
divided into smaller ones, which are then solved concurrently ("in parallel").
Asynchronous operation means that a process operates independently of other
processes. If there are multiple operations, [they] can be handled [using] different
processes/threads without waiting to complete the other ones.
When the flow of your program is such that code might be executed out
of order or you might not be able to count on one thing happening
before another thing.
But why does
(JavaScript) code run in
order in the first place?
// Define some functions
JS
function first() {
return 'hello';
}
function second() {
return first();
}
function third() {
first();
return second();
}
function fourth() {
first();
second();
return third();
}
// Execute the program
01 first();
02 second();
03 third();
04 fourth();
Code is executed in a "single thread."
// Define some functions
JS
01 function last() {
02 console.log("from L.A. to Tokyo");
03 }
04 function doProgram() {
05 setTimeout(last, 0);
06 console.log("i'm so fancy");
07 console.log("you already know");
08 console.log("i'm in the fast lane");
09 }
// Execute the program
10 doProgram();
!
//=> i'm so fancy
//=> you already know
//=> i'm in the fast lane
//=> from L.A. to Tokyo
“
When there is nothing to do,
Check the queue.
But only check the queue
When there's nothing left to do.
- JavaScript
In other words, the current flow will NEVER be
interrupted by code existing in the queue.
// Add a click handler to the document.
document.addEventListener('click', function () {
console.log('click happened!');
});
!
// Create a function that does nothing but waste time.
function wasteTime() {
var i;
for (i = 0; i < 3000000; i += 1) {
new Array(10000000);
}
return 'finished wasting time';
}
!
// Start wasting time.
wasteTime();
JS
//=> finished wasting time
//=> click happened!
Let's prove it in the console!
JS
Some similar examples that
use the queue:
[ELEMENT].addEventListener('click', myFunction);
!
[ELEMENT].onclick = myFunction;
!
$([ELEMENT]).click(myFunction);
!
<a onclick="myFunction">click me</a>
The queue matters because any time your program
receives input, JavaScript puts the input handler
into the queue.
So when we talk about
"asynchronous JavaScript,"
we're really just talking
about any code that puts
things in the queue.
And if we can't know when code
will enter the queue (for example,
application input), we can't
know when it will be executed.
1 2 3
Ways to Receive Input
DOM events such as
clicks, hovers, keyups,
etc.
!
!
Handlers go in the
queue.
HTTP(s)/websocket
communication events.
(Includes $.ajax)
!
!
Handlers go in the
queue.
Web worker message
passing. (How we do
threads in the browser)
!
!
Handlers go in the
queue.
And if it's in the queue,
you can't return it or
error handle it.
function getGithubInfo() {
var ajax = $.ajax({
url: 'https://api.github.com/users/jgnewman/repos',
dataType: 'jsonp'
});
return ajax;
}
!
getGithubInfo();
JSLet's access some real data:
function getGithubInfo() {
var ajax = $.ajax({
url: 'https://api.github.com/users/jgnewman/repos',
dataType: 'jsonp'
});
return ajax;
}
!
getGithubInfo();
JSLet's access some real data:
NOPE!
But clearly that's because $.ajax is returning the jQuery
request object instead of the actual data. Let's fix that.
function getGithubInfo() {
var ajax = $.ajax({
url: 'https://api.github.com/users/jgnewman/repos',
dataType: 'jsonp'
});
return ajax.done(function (data) {
return data;
});
}
!
getGithubInfo();
JSLet's access some real data:
function getGithubInfo() {
var ajax = $.ajax({
url: 'https://api.github.com/users/jgnewman/repos',
dataType: 'jsonp'
});
return ajax.done(function (data) {
return data;
});
}
!
getGithubInfo();
JSLet's access some real data:
STILL NOPE!
Right, but this time it's because .done is a Promise method so it's
returning another Promise object. I got it this time…
function getGithubInfo() {
var result;
$.ajax({
url: 'https://api.github.com/users/jgnewman/repos',
dataType: 'jsonp'
}).done(function (data) {
result = data;
});
return result;
}
!
getGithubInfo();
JSLet's access some real data:
function getGithubInfo() {
var result;
$.ajax({
url: 'https://api.github.com/users/jgnewman/repos',
dataType: 'jsonp'
}).done(function (data) {
result = data;
});
return result;
}
!
getGithubInfo();
JSLet's access some real data:
FRACK! STILL NOPE!
Because no matter what we do, ajax requires an event handler and
event handlers go into the queue. Which means…
It gets executed AFTER
the function returns.
function logResult(result) {
console.log(result);
}
!
function getGithubInfo() {
var ajax = $.ajax({
url: 'https://api.github.com/users/jgnewman/repos',
dataType: 'jsonp'
});
ajax.done(logResult);
}
!
getGithubInfo();
JSThis time let's really do it:
function logResult(result) {
console.log(result);
}
!
function getGithubInfo() {
var ajax = $.ajax({
url: 'https://api.github.com/users/jgnewman/repos',
dataType: 'jsonp'
});
ajax.done(logResult);
}
!
getGithubInfo();
JSThis time let's really do it:
SUCCESS!
What was that you said
about error handling?
function logResult(result) {
console.log(result);
}
!
function getGithubInfo() {
var ajax;
try {
ajax = $.ajax({
url: 'fhqwhgads',
dataType: 'jsonp'
});
ajax.done(logResult);
} catch (err) {
console.log('got an error', err);
}
}
!
getGithubInfo();
JSNo error handling allowed:
function logResult(result) {
console.log(result);
}
!
function getGithubInfo() {
var ajax = $.ajax({
url: 'fhqwhgads',
dataType: 'jsonp'
});
ajax.done(logResult);
ajax.fail(function (errData) {
console.log('got an error', errData);
});
}
!
getGithubInfo();
JSThe jQuery Solution:
Asynchrony can be
hard to reason about
when it gets complex.
So let's talk about some common techniques that can
make it feel more synchronous.
CALLBACK FUNCTIONS
PROMISE OBJECTS
// Import the file system library
var fileSystem = require('fs');
!
// Call `readdir` (which is asynchronous) to get a list
// of files in the directory
fileSystem.readdir('/myfiles', function (err, data) {
if (err) {
handleTheError(err);
} else {
doSomethingWith(data);
}
});
JSWhat Everyone Hates About
Node.js
What's wrong with this pattern, you ask?
/**
* Show a list of songs for the artist with the given name and
* execute the callback when complete.
*/
function showSongs(artistName, callback) {
// Notice we're not even thinking about errors here
artists.getByName(artistName, function (artist) {
albums.getByArtist(artist, function (albums) {
songs.getByAlbum(albums, function (songs) {
songView.render(songs);
return callback();
});
});
});
}
JSThe fact that it gets nasty
really fast:
example stolen from clutchski on slideshare
Can Promises fix that
problem?
The can definitely ice that cake.
What is a Promise?
‣ It's an object with methods (usually done, then, and fail).
‣ Each method takes at least 1 callback.
‣ The callbacks are executed under different conditions
(done or then on success, fail on error ).
‣ Each Promise method returns another promise.
‣ Therefore, you can chain asynchronous actions.
‣ And you can attach as many callbacks as you want to a
given event.
function myAsyncFn() {
return new Promise(function (resolve, reject) {
var async = somethingAsynchronous();
async.addEventListener('success', resolve());
async.addEventListener('error', reject());
});
}
JSFor example:
var myPromise = myAsyncFn();
myPromise.done(function () { …success stuff… });
myPromise.done(function () { …more success stuff… });
myPromise.fail(function () { …failure stuff… });
myPromise.fail(function () { …more failure stuff… });
myPromise.then(function () { return myAsyncFn() })
.then(function () { return myAsyncFn() })
.then(function () { return myAsyncFn() });
So let's go back to our
ugly, nested callbacks.
/**
* Show a list of songs for the artist with the given name and
* execute the callback when complete.
*/
function showSongs(artistName, callback) {
artists.getByName(artistName, function (artist) {
albums.getByArtist(artist, function (albums) {
songs.getByAlbum(albums, function (songs) {
songView.render(songs);
return callback();
});
});
});
}
JSPreviously we had this:
/**
* Show a list of songs for the artist with the given name and
* execute the callback when complete.
*/
function showSongs(artistName, callback) {
artists.getByName(artistName)
.then(function (artist) { return albums.getByArtist(artist) })
.then(function (albums) { return songs.getByAlbum(albums) })
.then(function (songs) { return songView.render(songs) })
.then(callback);
}
JSBut if we used promises
instead…
Promises are going to be native in ES6! (Currently 0 IE support)
jQuery
Tons of Others
Q for Node.js
http://api.jquery.com/promise/
http://promisesaplus.com/implementations
https://github.com/kriskowal/q
At this point, you may be
wondering…
‣ Why asynchrony is always talked about in terms of
concurrency when the word itself seems to imply the
exact opposite
‣ What asynchronous JavaScript looks like using web
workers
‣ When this talk is going to end
(Check the time, future John)
Concurrency becomes
asynchrony when
parallel threads talk to
each other.
Evaluate main
thread and worker
thread
JS
Queue
Queue
Main thread sends
message to worker
which goes into
the worker's
queue
Worker sends
message to main
thread which goes
into main
thread's queue
Each thread can be
run on its own core
thus making multiple
actions actually
simultaneous.
Every time a message
is sent, that message
goes into a queue
thus making the code
within each thread
independently
asynchronous.
A web worker is…
‣ A way to spin up multiple threads in browser-based
JavaScript
‣ Theoretically, an extremely helpful tool that has been
much needed for quite some time
‣ In reality, a fairly annoying and cumbersome
implementation of a concept that ought to have been
much simpler
JS
var worker = new Worker('myworker.js');
!
worker.onmessage = function (evt) {
console.log('The worker sent', evt.data);
};
!
worker.postMessage('');
JS
self.onmessage = function () {
self.postMessage('message received');
};
main.js myworker.js
// Takes a function and turns it into a web worker
function createWorker(fn) {
var body = fn.toString().replace(/^.+{|}s*$/g, ''),
blob = new Blob([body], {type: 'text/javascript'});
return new Worker(window.URL.createObjectURL(blob));
}
JS
There's also a "secret" way to do it
with one file:
// The intended functionality of our web worker
function workerBody() {
self.onmessage = function () {
self.postMessage('message received');
};
}
// Create and use the worker
var worker = createWorker(workerBody);
worker.onmessage = function (evt) {
console.log('The worker sent', evt.data);
};
worker.postMessage('');
JS
Let's use it to make life a bit easier:
// The minified worker maker
function createWorker(f){var b=f.toString().replace(/^.+{|}s*$/g,''),l=new
Blob([b],{type:'text/javascript'});return new Worker(window.URL.createObjectURL(l))}
!
// A worker body containing a modified version of our time wasting function from before.
// Creates 3 million arrays with 10 million items and returns the amount of
// time that took.
function workerBody() {
function wasteTime() {
var i, begin = Date.now();
for (i = 0; i < 3000000; i += 1) {
new Array(10000000);
}
return Date.now() - begin;
}
self.onmessage = function () {
var time = wasteTime();
self.postMessage('Wasted ' + time + 'ms of time.');
};
}
!
// Set up a click handler on the document
var clicks = 0;
document.addEventListener('click', function () { console.log('click', ++clicks, 'happened') });
!
// Launch the worker and try it out.
var worker = createWorker(workerBody);
worker.onmessage = function (evt) { console.log(evt.data) };
worker.postMessage();
Check out where I
actually use this
concept…
STREAMPUNK
!
A simple & surprisingly powerful
application framework that offers data
binding, single page apps, and tons of
other tools.
!
streampunkjs.com
SOLID FUEL
SOCKET BOOSTER
!
A library for the browser that allows you
to take common ajax/websocket actions
and dynamically run them within a web
worker.
!
github.com/jgnewman/sfsb
You can also check out
htmlgoodies.com for
more examples of Web
Workers in action.
http://www.htmlgoodies.com/html5/client/introduction-
to-html5-web-workers-use-cases-and-identify-hot-
spots-.html
THANK YOU!
John Newman
@jnewmanux
rescuecreative@gmail.com

Contenu connexe

Tendances

Javascript Promises/Q Library
Javascript Promises/Q LibraryJavascript Promises/Q Library
Javascript Promises/Q Libraryasync_io
 
The Promised Land (in Angular)
The Promised Land (in Angular)The Promised Land (in Angular)
The Promised Land (in Angular)Domenic Denicola
 
$q and Promises in AngularJS
$q and Promises in AngularJS $q and Promises in AngularJS
$q and Promises in AngularJS a_sharif
 
JavaScript Promises
JavaScript PromisesJavaScript Promises
JavaScript PromisesTomasz Bak
 
Avoiding callback hell with promises
Avoiding callback hell with promisesAvoiding callback hell with promises
Avoiding callback hell with promisesTorontoNodeJS
 
Practical JavaScript Promises
Practical JavaScript PromisesPractical JavaScript Promises
Practical JavaScript PromisesAsa Kusuma
 
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Domenic Denicola
 
JavaScript promise
JavaScript promiseJavaScript promise
JavaScript promiseeslam_me
 
Java Script Promise
Java Script PromiseJava Script Promise
Java Script PromiseAlok Guha
 
Getting Comfortable with JS Promises
Getting Comfortable with JS PromisesGetting Comfortable with JS Promises
Getting Comfortable with JS PromisesAsa Kusuma
 
5 Tips for Better JavaScript
5 Tips for Better JavaScript5 Tips for Better JavaScript
5 Tips for Better JavaScriptTodd Anglin
 
Boom! Promises/A+ Was Born
Boom! Promises/A+ Was BornBoom! Promises/A+ Was Born
Boom! Promises/A+ Was BornDomenic Denicola
 
Introduction to reactive programming & ReactiveCocoa
Introduction to reactive programming & ReactiveCocoaIntroduction to reactive programming & ReactiveCocoa
Introduction to reactive programming & ReactiveCocoaFlorent Pillet
 
Node.js: Continuation-Local-Storage and the Magic of AsyncListener
Node.js: Continuation-Local-Storage and the Magic of AsyncListenerNode.js: Continuation-Local-Storage and the Magic of AsyncListener
Node.js: Continuation-Local-Storage and the Magic of AsyncListenerIslam Sharabash
 

Tendances (20)

Javascript Promises/Q Library
Javascript Promises/Q LibraryJavascript Promises/Q Library
Javascript Promises/Q Library
 
JavaScript Promises
JavaScript PromisesJavaScript Promises
JavaScript Promises
 
Promise pattern
Promise patternPromise pattern
Promise pattern
 
The Promised Land (in Angular)
The Promised Land (in Angular)The Promised Land (in Angular)
The Promised Land (in Angular)
 
$q and Promises in AngularJS
$q and Promises in AngularJS $q and Promises in AngularJS
$q and Promises in AngularJS
 
JavaScript Promises
JavaScript PromisesJavaScript Promises
JavaScript Promises
 
Avoiding callback hell with promises
Avoiding callback hell with promisesAvoiding callback hell with promises
Avoiding callback hell with promises
 
Practical JavaScript Promises
Practical JavaScript PromisesPractical JavaScript Promises
Practical JavaScript Promises
 
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
 
JavaScript promise
JavaScript promiseJavaScript promise
JavaScript promise
 
Java Script Promise
Java Script PromiseJava Script Promise
Java Script Promise
 
Getting Comfortable with JS Promises
Getting Comfortable with JS PromisesGetting Comfortable with JS Promises
Getting Comfortable with JS Promises
 
JavaScript Promises
JavaScript PromisesJavaScript Promises
JavaScript Promises
 
5 Tips for Better JavaScript
5 Tips for Better JavaScript5 Tips for Better JavaScript
5 Tips for Better JavaScript
 
Boom! Promises/A+ Was Born
Boom! Promises/A+ Was BornBoom! Promises/A+ Was Born
Boom! Promises/A+ Was Born
 
Introduction to reactive programming & ReactiveCocoa
Introduction to reactive programming & ReactiveCocoaIntroduction to reactive programming & ReactiveCocoa
Introduction to reactive programming & ReactiveCocoa
 
Async Frontiers
Async FrontiersAsync Frontiers
Async Frontiers
 
Node.js: Continuation-Local-Storage and the Magic of AsyncListener
Node.js: Continuation-Local-Storage and the Magic of AsyncListenerNode.js: Continuation-Local-Storage and the Magic of AsyncListener
Node.js: Continuation-Local-Storage and the Magic of AsyncListener
 
Java script for web developer
Java script for web developerJava script for web developer
Java script for web developer
 
ES6: The Awesome Parts
ES6: The Awesome PartsES6: The Awesome Parts
ES6: The Awesome Parts
 

Similaire à Understanding Asynchronous JavaScript

Asynchronous development in JavaScript
Asynchronous development  in JavaScriptAsynchronous development  in JavaScript
Asynchronous development in JavaScriptAmitai Barnea
 
The evolution of java script asynchronous calls
The evolution of java script asynchronous callsThe evolution of java script asynchronous calls
The evolution of java script asynchronous callsHuy Hoàng Phạm
 
Angular promises and http
Angular promises and httpAngular promises and http
Angular promises and httpAlexe Bogdan
 
02 Introduction to Javascript
02 Introduction to Javascript02 Introduction to Javascript
02 Introduction to Javascriptcrgwbr
 
Intro to Asynchronous Javascript
Intro to Asynchronous JavascriptIntro to Asynchronous Javascript
Intro to Asynchronous JavascriptGarrett Welson
 
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
 
IS YOUR WIDGET FAST? FIVE BEST PRACTICES TO FASTER EMBEDDABLE CONTENT
IS YOUR WIDGET FAST? FIVE BEST PRACTICES TO FASTER EMBEDDABLE CONTENTIS YOUR WIDGET FAST? FIVE BEST PRACTICES TO FASTER EMBEDDABLE CONTENT
IS YOUR WIDGET FAST? FIVE BEST PRACTICES TO FASTER EMBEDDABLE CONTENTIsmail Elshareef
 
Expert JavaScript tricks of the masters
Expert JavaScript  tricks of the mastersExpert JavaScript  tricks of the masters
Expert JavaScript tricks of the mastersAra Pehlivanian
 
From Node.js to Design Patterns - BuildPiper
From Node.js to Design Patterns - BuildPiperFrom Node.js to Design Patterns - BuildPiper
From Node.js to Design Patterns - BuildPiperLuciano Mammino
 
Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...
Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...
Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...GITS Indonesia
 
Service worker - Offline Web
Service worker - Offline WebService worker - Offline Web
Service worker - Offline WebBruno Oliveira
 
Even more java script best practices
Even more java script best practicesEven more java script best practices
Even more java script best practicesChengHui Weng
 
Promises - Asynchronous Control Flow
Promises - Asynchronous Control FlowPromises - Asynchronous Control Flow
Promises - Asynchronous Control FlowHenrique Barcelos
 
Lazy Loading Because I'm Lazy
Lazy Loading Because I'm LazyLazy Loading Because I'm Lazy
Lazy Loading Because I'm LazyJohnathan Leppert
 
Think Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSThink Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSAdam L Barrett
 
Extending Ajax Events for all mankind
Extending Ajax Events for all mankindExtending Ajax Events for all mankind
Extending Ajax Events for all mankindKyle Simpson
 

Similaire à Understanding Asynchronous JavaScript (20)

Asynchronous development in JavaScript
Asynchronous development  in JavaScriptAsynchronous development  in JavaScript
Asynchronous development in JavaScript
 
The evolution of java script asynchronous calls
The evolution of java script asynchronous callsThe evolution of java script asynchronous calls
The evolution of java script asynchronous calls
 
Developing Async Sense
Developing Async SenseDeveloping Async Sense
Developing Async Sense
 
Angular promises and http
Angular promises and httpAngular promises and http
Angular promises and http
 
02 Introduction to Javascript
02 Introduction to Javascript02 Introduction to Javascript
02 Introduction to Javascript
 
Intro to Asynchronous Javascript
Intro to Asynchronous JavascriptIntro to Asynchronous Javascript
Intro to Asynchronous Javascript
 
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
 
IS YOUR WIDGET FAST? FIVE BEST PRACTICES TO FASTER EMBEDDABLE CONTENT
IS YOUR WIDGET FAST? FIVE BEST PRACTICES TO FASTER EMBEDDABLE CONTENTIS YOUR WIDGET FAST? FIVE BEST PRACTICES TO FASTER EMBEDDABLE CONTENT
IS YOUR WIDGET FAST? FIVE BEST PRACTICES TO FASTER EMBEDDABLE CONTENT
 
JavaScript for real men
JavaScript for real menJavaScript for real men
JavaScript for real men
 
Expert JavaScript tricks of the masters
Expert JavaScript  tricks of the mastersExpert JavaScript  tricks of the masters
Expert JavaScript tricks of the masters
 
From Node.js to Design Patterns - BuildPiper
From Node.js to Design Patterns - BuildPiperFrom Node.js to Design Patterns - BuildPiper
From Node.js to Design Patterns - BuildPiper
 
Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...
Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...
Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...
 
Service worker - Offline Web
Service worker - Offline WebService worker - Offline Web
Service worker - Offline Web
 
Even more java script best practices
Even more java script best practicesEven more java script best practices
Even more java script best practices
 
You promise?
You promise?You promise?
You promise?
 
Rxjs kyivjs 2015
Rxjs kyivjs 2015Rxjs kyivjs 2015
Rxjs kyivjs 2015
 
Promises - Asynchronous Control Flow
Promises - Asynchronous Control FlowPromises - Asynchronous Control Flow
Promises - Asynchronous Control Flow
 
Lazy Loading Because I'm Lazy
Lazy Loading Because I'm LazyLazy Loading Because I'm Lazy
Lazy Loading Because I'm Lazy
 
Think Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSThink Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJS
 
Extending Ajax Events for all mankind
Extending Ajax Events for all mankindExtending Ajax Events for all mankind
Extending Ajax Events for all mankind
 

Dernier

Blepharitis inflammation of eyelid symptoms cause everything included along w...
Blepharitis inflammation of eyelid symptoms cause everything included along w...Blepharitis inflammation of eyelid symptoms cause everything included along w...
Blepharitis inflammation of eyelid symptoms cause everything included along w...Excelmac1
 
PHP-based rendering of TYPO3 Documentation
PHP-based rendering of TYPO3 DocumentationPHP-based rendering of TYPO3 Documentation
PHP-based rendering of TYPO3 DocumentationLinaWolf1
 
Call Girls in Uttam Nagar Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Uttam Nagar Delhi 💯Call Us 🔝8264348440🔝Call Girls in Uttam Nagar Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Uttam Nagar Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一Fs
 
A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)
A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)
A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)Christopher H Felton
 
定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一
定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一
定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一Fs
 
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012rehmti665
 
Contact Rya Baby for Call Girls New Delhi
Contact Rya Baby for Call Girls New DelhiContact Rya Baby for Call Girls New Delhi
Contact Rya Baby for Call Girls New Delhimiss dipika
 
Magic exist by Marta Loveguard - presentation.pptx
Magic exist by Marta Loveguard - presentation.pptxMagic exist by Marta Loveguard - presentation.pptx
Magic exist by Marta Loveguard - presentation.pptxMartaLoveguard
 
Call Girls Near The Suryaa Hotel New Delhi 9873777170
Call Girls Near The Suryaa Hotel New Delhi 9873777170Call Girls Near The Suryaa Hotel New Delhi 9873777170
Call Girls Near The Suryaa Hotel New Delhi 9873777170Sonam Pathan
 
办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书
办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书
办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书zdzoqco
 
定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一
定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一
定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一Fs
 
Call Girls In The Ocean Pearl Retreat Hotel New Delhi 9873777170
Call Girls In The Ocean Pearl Retreat Hotel New Delhi 9873777170Call Girls In The Ocean Pearl Retreat Hotel New Delhi 9873777170
Call Girls In The Ocean Pearl Retreat Hotel New Delhi 9873777170Sonam Pathan
 
Top 10 Interactive Website Design Trends in 2024.pptx
Top 10 Interactive Website Design Trends in 2024.pptxTop 10 Interactive Website Design Trends in 2024.pptx
Top 10 Interactive Website Design Trends in 2024.pptxDyna Gilbert
 
Call Girls Service Adil Nagar 7001305949 Need escorts Service Pooja Vip
Call Girls Service Adil Nagar 7001305949 Need escorts Service Pooja VipCall Girls Service Adil Nagar 7001305949 Need escorts Service Pooja Vip
Call Girls Service Adil Nagar 7001305949 Need escorts Service Pooja VipCall Girls Lucknow
 
Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作
Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作
Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作ys8omjxb
 
Font Performance - NYC WebPerf Meetup April '24
Font Performance - NYC WebPerf Meetup April '24Font Performance - NYC WebPerf Meetup April '24
Font Performance - NYC WebPerf Meetup April '24Paul Calvano
 
Film cover research (1).pptxsdasdasdasdasdasa
Film cover research (1).pptxsdasdasdasdasdasaFilm cover research (1).pptxsdasdasdasdasdasa
Film cover research (1).pptxsdasdasdasdasdasa494f574xmv
 

Dernier (20)

Blepharitis inflammation of eyelid symptoms cause everything included along w...
Blepharitis inflammation of eyelid symptoms cause everything included along w...Blepharitis inflammation of eyelid symptoms cause everything included along w...
Blepharitis inflammation of eyelid symptoms cause everything included along w...
 
PHP-based rendering of TYPO3 Documentation
PHP-based rendering of TYPO3 DocumentationPHP-based rendering of TYPO3 Documentation
PHP-based rendering of TYPO3 Documentation
 
Call Girls in Uttam Nagar Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Uttam Nagar Delhi 💯Call Us 🔝8264348440🔝Call Girls in Uttam Nagar Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Uttam Nagar Delhi 💯Call Us 🔝8264348440🔝
 
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一
 
A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)
A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)
A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)
 
定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一
定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一
定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一
 
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
 
Contact Rya Baby for Call Girls New Delhi
Contact Rya Baby for Call Girls New DelhiContact Rya Baby for Call Girls New Delhi
Contact Rya Baby for Call Girls New Delhi
 
Magic exist by Marta Loveguard - presentation.pptx
Magic exist by Marta Loveguard - presentation.pptxMagic exist by Marta Loveguard - presentation.pptx
Magic exist by Marta Loveguard - presentation.pptx
 
Call Girls Near The Suryaa Hotel New Delhi 9873777170
Call Girls Near The Suryaa Hotel New Delhi 9873777170Call Girls Near The Suryaa Hotel New Delhi 9873777170
Call Girls Near The Suryaa Hotel New Delhi 9873777170
 
办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书
办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书
办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书
 
定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一
定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一
定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一
 
Call Girls In The Ocean Pearl Retreat Hotel New Delhi 9873777170
Call Girls In The Ocean Pearl Retreat Hotel New Delhi 9873777170Call Girls In The Ocean Pearl Retreat Hotel New Delhi 9873777170
Call Girls In The Ocean Pearl Retreat Hotel New Delhi 9873777170
 
Model Call Girl in Jamuna Vihar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in  Jamuna Vihar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in  Jamuna Vihar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Jamuna Vihar Delhi reach out to us at 🔝9953056974🔝
 
Top 10 Interactive Website Design Trends in 2024.pptx
Top 10 Interactive Website Design Trends in 2024.pptxTop 10 Interactive Website Design Trends in 2024.pptx
Top 10 Interactive Website Design Trends in 2024.pptx
 
Call Girls Service Adil Nagar 7001305949 Need escorts Service Pooja Vip
Call Girls Service Adil Nagar 7001305949 Need escorts Service Pooja VipCall Girls Service Adil Nagar 7001305949 Need escorts Service Pooja Vip
Call Girls Service Adil Nagar 7001305949 Need escorts Service Pooja Vip
 
Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作
Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作
Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作
 
Font Performance - NYC WebPerf Meetup April '24
Font Performance - NYC WebPerf Meetup April '24Font Performance - NYC WebPerf Meetup April '24
Font Performance - NYC WebPerf Meetup April '24
 
Hot Sexy call girls in Rk Puram 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in  Rk Puram 🔝 9953056974 🔝 Delhi escort ServiceHot Sexy call girls in  Rk Puram 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Rk Puram 🔝 9953056974 🔝 Delhi escort Service
 
Film cover research (1).pptxsdasdasdasdasdasa
Film cover research (1).pptxsdasdasdasdasdasaFilm cover research (1).pptxsdasdasdasdasdasa
Film cover research (1).pptxsdasdasdasdasdasa
 

Understanding Asynchronous JavaScript

  • 1. John Newman @jnewmanux • github.com/jgnewman rescuecreative@gmail.com UNDERSTANDING ASYNCHRONOUS JAVASCRIPT TallyJS - June 2014
  • 3. “There are two hard things in computer science: cache invalidation, naming things, and off-by-one errors. - Unknown Somebody go to Google and search "define synchronous"
  • 4. Wikipedia codewala.net Our Simple Definition Parallel computing is a form of computation in which many calculations are carried out simultaneously, operating on the principle that large problems can often be divided into smaller ones, which are then solved concurrently ("in parallel"). Asynchronous operation means that a process operates independently of other processes. If there are multiple operations, [they] can be handled [using] different processes/threads without waiting to complete the other ones. When the flow of your program is such that code might be executed out of order or you might not be able to count on one thing happening before another thing.
  • 5. But why does (JavaScript) code run in order in the first place?
  • 6. // Define some functions JS function first() { return 'hello'; } function second() { return first(); } function third() { first(); return second(); } function fourth() { first(); second(); return third(); } // Execute the program 01 first(); 02 second(); 03 third(); 04 fourth(); Code is executed in a "single thread."
  • 7. // Define some functions JS 01 function last() { 02 console.log("from L.A. to Tokyo"); 03 } 04 function doProgram() { 05 setTimeout(last, 0); 06 console.log("i'm so fancy"); 07 console.log("you already know"); 08 console.log("i'm in the fast lane"); 09 } // Execute the program 10 doProgram(); ! //=> i'm so fancy //=> you already know //=> i'm in the fast lane //=> from L.A. to Tokyo
  • 8. “ When there is nothing to do, Check the queue. But only check the queue When there's nothing left to do. - JavaScript In other words, the current flow will NEVER be interrupted by code existing in the queue.
  • 9. // Add a click handler to the document. document.addEventListener('click', function () { console.log('click happened!'); }); ! // Create a function that does nothing but waste time. function wasteTime() { var i; for (i = 0; i < 3000000; i += 1) { new Array(10000000); } return 'finished wasting time'; } ! // Start wasting time. wasteTime(); JS //=> finished wasting time //=> click happened! Let's prove it in the console!
  • 10. JS Some similar examples that use the queue: [ELEMENT].addEventListener('click', myFunction); ! [ELEMENT].onclick = myFunction; ! $([ELEMENT]).click(myFunction); ! <a onclick="myFunction">click me</a> The queue matters because any time your program receives input, JavaScript puts the input handler into the queue.
  • 11. So when we talk about "asynchronous JavaScript," we're really just talking about any code that puts things in the queue.
  • 12. And if we can't know when code will enter the queue (for example, application input), we can't know when it will be executed.
  • 13. 1 2 3 Ways to Receive Input DOM events such as clicks, hovers, keyups, etc. ! ! Handlers go in the queue. HTTP(s)/websocket communication events. (Includes $.ajax) ! ! Handlers go in the queue. Web worker message passing. (How we do threads in the browser) ! ! Handlers go in the queue.
  • 14. And if it's in the queue, you can't return it or error handle it.
  • 15. function getGithubInfo() { var ajax = $.ajax({ url: 'https://api.github.com/users/jgnewman/repos', dataType: 'jsonp' }); return ajax; } ! getGithubInfo(); JSLet's access some real data:
  • 16. function getGithubInfo() { var ajax = $.ajax({ url: 'https://api.github.com/users/jgnewman/repos', dataType: 'jsonp' }); return ajax; } ! getGithubInfo(); JSLet's access some real data: NOPE! But clearly that's because $.ajax is returning the jQuery request object instead of the actual data. Let's fix that.
  • 17. function getGithubInfo() { var ajax = $.ajax({ url: 'https://api.github.com/users/jgnewman/repos', dataType: 'jsonp' }); return ajax.done(function (data) { return data; }); } ! getGithubInfo(); JSLet's access some real data:
  • 18. function getGithubInfo() { var ajax = $.ajax({ url: 'https://api.github.com/users/jgnewman/repos', dataType: 'jsonp' }); return ajax.done(function (data) { return data; }); } ! getGithubInfo(); JSLet's access some real data: STILL NOPE! Right, but this time it's because .done is a Promise method so it's returning another Promise object. I got it this time…
  • 19. function getGithubInfo() { var result; $.ajax({ url: 'https://api.github.com/users/jgnewman/repos', dataType: 'jsonp' }).done(function (data) { result = data; }); return result; } ! getGithubInfo(); JSLet's access some real data:
  • 20. function getGithubInfo() { var result; $.ajax({ url: 'https://api.github.com/users/jgnewman/repos', dataType: 'jsonp' }).done(function (data) { result = data; }); return result; } ! getGithubInfo(); JSLet's access some real data: FRACK! STILL NOPE! Because no matter what we do, ajax requires an event handler and event handlers go into the queue. Which means…
  • 21. It gets executed AFTER the function returns.
  • 22. function logResult(result) { console.log(result); } ! function getGithubInfo() { var ajax = $.ajax({ url: 'https://api.github.com/users/jgnewman/repos', dataType: 'jsonp' }); ajax.done(logResult); } ! getGithubInfo(); JSThis time let's really do it:
  • 23. function logResult(result) { console.log(result); } ! function getGithubInfo() { var ajax = $.ajax({ url: 'https://api.github.com/users/jgnewman/repos', dataType: 'jsonp' }); ajax.done(logResult); } ! getGithubInfo(); JSThis time let's really do it: SUCCESS!
  • 24. What was that you said about error handling?
  • 25. function logResult(result) { console.log(result); } ! function getGithubInfo() { var ajax; try { ajax = $.ajax({ url: 'fhqwhgads', dataType: 'jsonp' }); ajax.done(logResult); } catch (err) { console.log('got an error', err); } } ! getGithubInfo(); JSNo error handling allowed:
  • 26. function logResult(result) { console.log(result); } ! function getGithubInfo() { var ajax = $.ajax({ url: 'fhqwhgads', dataType: 'jsonp' }); ajax.done(logResult); ajax.fail(function (errData) { console.log('got an error', errData); }); } ! getGithubInfo(); JSThe jQuery Solution:
  • 27. Asynchrony can be hard to reason about when it gets complex. So let's talk about some common techniques that can make it feel more synchronous.
  • 29. // Import the file system library var fileSystem = require('fs'); ! // Call `readdir` (which is asynchronous) to get a list // of files in the directory fileSystem.readdir('/myfiles', function (err, data) { if (err) { handleTheError(err); } else { doSomethingWith(data); } }); JSWhat Everyone Hates About Node.js What's wrong with this pattern, you ask?
  • 30. /** * Show a list of songs for the artist with the given name and * execute the callback when complete. */ function showSongs(artistName, callback) { // Notice we're not even thinking about errors here artists.getByName(artistName, function (artist) { albums.getByArtist(artist, function (albums) { songs.getByAlbum(albums, function (songs) { songView.render(songs); return callback(); }); }); }); } JSThe fact that it gets nasty really fast: example stolen from clutchski on slideshare
  • 31. Can Promises fix that problem? The can definitely ice that cake.
  • 32. What is a Promise? ‣ It's an object with methods (usually done, then, and fail). ‣ Each method takes at least 1 callback. ‣ The callbacks are executed under different conditions (done or then on success, fail on error ). ‣ Each Promise method returns another promise. ‣ Therefore, you can chain asynchronous actions. ‣ And you can attach as many callbacks as you want to a given event.
  • 33. function myAsyncFn() { return new Promise(function (resolve, reject) { var async = somethingAsynchronous(); async.addEventListener('success', resolve()); async.addEventListener('error', reject()); }); } JSFor example: var myPromise = myAsyncFn(); myPromise.done(function () { …success stuff… }); myPromise.done(function () { …more success stuff… }); myPromise.fail(function () { …failure stuff… }); myPromise.fail(function () { …more failure stuff… }); myPromise.then(function () { return myAsyncFn() }) .then(function () { return myAsyncFn() }) .then(function () { return myAsyncFn() });
  • 34. So let's go back to our ugly, nested callbacks.
  • 35. /** * Show a list of songs for the artist with the given name and * execute the callback when complete. */ function showSongs(artistName, callback) { artists.getByName(artistName, function (artist) { albums.getByArtist(artist, function (albums) { songs.getByAlbum(albums, function (songs) { songView.render(songs); return callback(); }); }); }); } JSPreviously we had this:
  • 36. /** * Show a list of songs for the artist with the given name and * execute the callback when complete. */ function showSongs(artistName, callback) { artists.getByName(artistName) .then(function (artist) { return albums.getByArtist(artist) }) .then(function (albums) { return songs.getByAlbum(albums) }) .then(function (songs) { return songView.render(songs) }) .then(callback); } JSBut if we used promises instead… Promises are going to be native in ES6! (Currently 0 IE support)
  • 37. jQuery Tons of Others Q for Node.js http://api.jquery.com/promise/ http://promisesaplus.com/implementations https://github.com/kriskowal/q
  • 38. At this point, you may be wondering… ‣ Why asynchrony is always talked about in terms of concurrency when the word itself seems to imply the exact opposite ‣ What asynchronous JavaScript looks like using web workers ‣ When this talk is going to end (Check the time, future John)
  • 39. Concurrency becomes asynchrony when parallel threads talk to each other.
  • 40. Evaluate main thread and worker thread JS Queue Queue Main thread sends message to worker which goes into the worker's queue Worker sends message to main thread which goes into main thread's queue Each thread can be run on its own core thus making multiple actions actually simultaneous. Every time a message is sent, that message goes into a queue thus making the code within each thread independently asynchronous.
  • 41. A web worker is… ‣ A way to spin up multiple threads in browser-based JavaScript ‣ Theoretically, an extremely helpful tool that has been much needed for quite some time ‣ In reality, a fairly annoying and cumbersome implementation of a concept that ought to have been much simpler
  • 42. JS var worker = new Worker('myworker.js'); ! worker.onmessage = function (evt) { console.log('The worker sent', evt.data); }; ! worker.postMessage(''); JS self.onmessage = function () { self.postMessage('message received'); }; main.js myworker.js
  • 43. // Takes a function and turns it into a web worker function createWorker(fn) { var body = fn.toString().replace(/^.+{|}s*$/g, ''), blob = new Blob([body], {type: 'text/javascript'}); return new Worker(window.URL.createObjectURL(blob)); } JS There's also a "secret" way to do it with one file: // The intended functionality of our web worker function workerBody() { self.onmessage = function () { self.postMessage('message received'); }; } // Create and use the worker var worker = createWorker(workerBody); worker.onmessage = function (evt) { console.log('The worker sent', evt.data); }; worker.postMessage('');
  • 44. JS Let's use it to make life a bit easier: // The minified worker maker function createWorker(f){var b=f.toString().replace(/^.+{|}s*$/g,''),l=new Blob([b],{type:'text/javascript'});return new Worker(window.URL.createObjectURL(l))} ! // A worker body containing a modified version of our time wasting function from before. // Creates 3 million arrays with 10 million items and returns the amount of // time that took. function workerBody() { function wasteTime() { var i, begin = Date.now(); for (i = 0; i < 3000000; i += 1) { new Array(10000000); } return Date.now() - begin; } self.onmessage = function () { var time = wasteTime(); self.postMessage('Wasted ' + time + 'ms of time.'); }; } ! // Set up a click handler on the document var clicks = 0; document.addEventListener('click', function () { console.log('click', ++clicks, 'happened') }); ! // Launch the worker and try it out. var worker = createWorker(workerBody); worker.onmessage = function (evt) { console.log(evt.data) }; worker.postMessage();
  • 45. Check out where I actually use this concept…
  • 46. STREAMPUNK ! A simple & surprisingly powerful application framework that offers data binding, single page apps, and tons of other tools. ! streampunkjs.com SOLID FUEL SOCKET BOOSTER ! A library for the browser that allows you to take common ajax/websocket actions and dynamically run them within a web worker. ! github.com/jgnewman/sfsb
  • 47. You can also check out htmlgoodies.com for more examples of Web Workers in action. http://www.htmlgoodies.com/html5/client/introduction- to-html5-web-workers-use-cases-and-identify-hot- spots-.html