SlideShare a Scribd company logo
1 of 31
Download to read offline
6th of June, 2015
Asynchronous Javascript
Common and useful patterns
by Steven Rémot
6th of June, 2015
Table of contents
1. Callbacks
2. Promises
3. Generators
6th of June, 2015
Table of contents
1. Callbacks
2. Promises
3. Generators
6th of June, 2015
Callbacks - Usage
function GameController() {
var dirChangedCb = function () {};
this.onDirectionChanged = function (callback) {
dirChangedCb = callback;
};
document.addEventListener('keydown', function (event) {
dirChangedCb(determineEventDirection(event));
});
}
var gc = new GameController();
gc.onDirectionChanged(function (direction) {
hero.move(direction);
});
6th of June, 2015
Callbacks - Avoiding conflicts
function GameController() {
var dirChangedCb = function () {};
this.onDirectionChanged = function (callback) {
dirChangedCb = callback;
};
document.addEventListener('keydown', function (event) {
dirChangedCb(determineEventDirection(event));
});
}
var gc = new GameController();
gc.onDirectionChanged(function (direction) {
hero.move(direction);
});
gc.onDirectionChanged(function (direction) {
enemy.reactTo(direction);
});
Only one callback is saved
6th of June, 2015
Callbacks - Avoiding conflicts
function GameController() {
var dirChangedCbs = [];
this.onDirectionChanged = function (callback) {
dirChangedCbs.push(callback);
};
document.addEventListener('keydown', function (event) {
for (var i = 0; i < dirChangedCbs.length; i++) {
dirChangedCbs[i](determineEventDirection(event));
}
});
}
var gc = new GameController();
gc.onDirectionChanged(function (direction) {
hero.move(direction);
});
gc.onDirectionChanged(function (direction) {
enemy.reactTo(direction);
});
6th of June, 2015
Callbacks - Nested operations
function loadHero(loadingFinishedCallback) {
http.get('/characters/hero.json', function (heroData) {
loadingFinishedCallback({ data: heroData });
});
}
6th of June, 2015
Callbacks - Nested operations
function loadHero(loadingFinishedCallback) {
http.get('/characters/hero.json', function (heroData) {
http.get(heroData.modelUrl, function (model) {
loadingFinishedCallback({
data: heroData,
model: model
});
});
});
}
6th of June, 2015
Callbacks - Nested operations
function loadHero(loadingFinishedCallback) {
http.get('/characters/hero.json', function (heroData) {
http.get(heroData.modelUrl, function (model) {
http.get(model.materialUrl, function (material) {
loadingFinishedCallback({
data: heroData,
model: model,
material: material
});
});
});
});
}
6th of June, 2015
Callbacks - Nested operations
function loadHero(loadingFinishedCallback) {
http.get('/characters/hero.json', function (heroData) {
loadGraphics(heroData.modelUrl, function (graphics) {
loadingFinishedCallback({
data: heroData,
model: graphics.model,
material: graphics.material
});
});
});
}
6th of June, 2015
Callbacks - Limits
● Nested callbacks are not handy
● Even worse with error catching
● Waiting for multiple callbacks is hard
Callbacks are bad for async operations
6th of June, 2015
Table of contents
1. Callbacks
2. Promises
3. Generators
6th of June, 2015
Promises - Basics
function httpGet(url) {
return new Promise(function (resolve) {
http.get(url, function (data) {
resolve(data);
});
});
}
6th of June, 2015
Promises - Basics
function httpGet(url) {
return new Promise(function (resolve) {
http.get(url, resolve);
});
}
6th of June, 2015
Promises - Basics
function httpGet(url) {
return new Promise(function (resolve, reject) {
http.get(url, resolve, reject);
});
}
6th of June, 2015
Promises - Chaining
function loadHero() {
return httpGet('/characters/hero.json')
.then(function (heroData) {
return {
data: heroData
};
});
}
loadHero().then(function (hero) {
console.log(hero.data);
});
6th of June, 2015
Promises - Chaining
function loadHero() {
return httpGet('/characters/hero.json')
.then(function (heroData) {
return httpGet(heroData.modelUrl).then(function (model) {
return {
data: heroData,
model: model
};
});
});
}
loadHero().then(function (hero) {
console.log(hero.data);
console.log(hero.model);
});
6th of June, 2015
Promises - Chaining
function loadHero() {
var hero = {};
return httpGet('/characters/hero.json')
.then(function (heroData) {
hero.data = heroData;
return httpGet(heroData.modelUrl);
})
.then(function (model) {
hero.model = model;
return hero;
});
}
loadHero().then(function (hero) {
console.log(hero.data);
console.log(hero.model);
});
6th of June, 2015
Promises - Chaining
function loadHero() {
var hero = {};
return httpGet('/characters/hero.json')
.then(function (heroData) {
hero.data = heroData;
return httpGet(heroData.modelUrl);
})
.then(function (model) {
hero.model = model;
return httpGet(model.materialUrl);
})
.then(function (material) {
hero.material = material;
return hero;
});
}
6th of June, 2015
Promises - Chaining
function loadHero() {
var hero = {};
return httpGet('/characters/hero.json')
.then(function (heroData) {
hero.data = heroData;
return httpGet(heroData.modelUrl);
})
.then(function (model) {
hero.model = model;
return httpGet(model.materialUrl);
})
.then(function (material) {
hero.material = material;
return hero;
})
.catch(function (error) {
console.log(error);
return null;
});
6th of June, 2015
Promises - Waiting all promises
function loadObjects() {
return Promise.all([
loadHero(),
loadEnemy(),
loadDoor(),
loadWall(),
// ...
]);
}
loadObjects().then(function (objects) {
var hero = objects[0];
var enemy = objects[1];
// ...
});
6th of June, 2015
Promises - How to get them
● In Ecmascript 6 standard library
● Available through polyfills:
https://github.com/jakearchibald/es6-promise
● Alternative APIs:
https://github.com/kriskowal/q
https://github.com/petkaantonov/bluebird
6th of June, 2015
Promises
Nice, but…
● Verbose
● Still writing in an asynchronous way
We can do better!
6th of June, 2015
Table of contents
1. Callbacks
2. Promises
3. Generators
6th of June, 2015
Generator - Basics
function* counter() {
for (var i = 0; i < 10; i++) {
yield i;
}
}
var count = counter();
console.log(count.next()); // 0
console.log(count.next()); // 1
// ...
6th of June, 2015
Generator - Basics
function* loadHero()
{
var hero = {};
hero.data = yield httpGet('/characters/hero.json');
hero.model = yield httpGet(hero.data.modelUrl);
hero.material = yield httpGet(hero.model.materialUrl);
return hero;
}
spawn(loadHero).then(function (hero) {
console.log(hero); // { data: <...>, model: <...>, ... }
});
6th of June, 2015
Generator - Basics
function* loadHero()
{
var hero = {};
try {
hero.data = yield httpGet('/characters/hero.json');
hero.model = yield httpGet(hero.data.modelUrl);
hero.material = yield httpGet(hero.model.materialUrl);
} catch (error) {
console.log(error);
hero = null;
}
return hero;
}
spawn(loadHero).then(function (hero) {
console.log(hero); // { data: <...>, model: <...>, ... }
});
6th of June, 2015
Generator - Basics
async function loadHero()
{
var hero = {};
try {
hero.data = await httpGet('/characters/hero.json');
hero.model = await httpGet(hero.data.modelUrl);
hero.material = await httpGet(hero.model.materialUrl);
} catch (error) {
console.log(error);
hero = null;
}
return hero;
}
loadHero().then(function () {
console.log(hero); // { data: <...>, model: <...>, ... }
});
6th of June, 2015
Generator - Browser support
● Generator are ES6
● Async functions are ES7
● Use them today with transpilers:
https://github.com/google/traceur-compiler
https://babeljs.io/
6th of June, 2015
Thanks for listening!
References:
https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Promise
https://www.promisejs.org/
https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Instructions/function*
https://github.com/lukehoban/ecmascript-asyncawait
6th of June, 2015
Join the community !
(in Paris)
Social networks :
● Follow us on Twitter : https://twitter.com/steamlearn
● Like us on Facebook : https://www.facebook.com/steamlearn
SteamLearn is an Inovia initiative : inovia.fr
You wish to be in the audience ? Join the meetup group!
http://www.meetup.com/Steam-Learn/

More Related Content

What's hot

Provisioning & Migration with p2: Case study - The Good, the Bad and the Ugly
Provisioning & Migration with p2: Case study - The Good, the Bad and the UglyProvisioning & Migration with p2: Case study - The Good, the Bad and the Ugly
Provisioning & Migration with p2: Case study - The Good, the Bad and the Uglychristianbourgeois
 
Redux. From twitter hype to production
Redux. From twitter hype to productionRedux. From twitter hype to production
Redux. From twitter hype to productionFDConf
 
The Ring programming language version 1.10 book - Part 82 of 212
The Ring programming language version 1.10 book - Part 82 of 212The Ring programming language version 1.10 book - Part 82 of 212
The Ring programming language version 1.10 book - Part 82 of 212Mahmoud Samir Fayed
 
[Android] PLAYING WITH FRAGMENT
[Android] PLAYING WITH FRAGMENT[Android] PLAYING WITH FRAGMENT
[Android] PLAYING WITH FRAGMENTJun Shimizu
 
Introduction to Angular js
Introduction to Angular jsIntroduction to Angular js
Introduction to Angular jsMustafa Gamal
 
View controller life cycle
View controller life cycleView controller life cycle
View controller life cycleSV.CO
 
Asynchronous CompletableFuture Presentation by László-Róbert Albert @Crossover
Asynchronous CompletableFuture Presentation by László-Róbert Albert @CrossoverAsynchronous CompletableFuture Presentation by László-Róbert Albert @Crossover
Asynchronous CompletableFuture Presentation by László-Róbert Albert @CrossoverCrossover Romania
 
Lowering in C#: What really happens with your code?, from NDC Oslo 2019
Lowering in C#: What really happens with your code?, from NDC Oslo 2019Lowering in C#: What really happens with your code?, from NDC Oslo 2019
Lowering in C#: What really happens with your code?, from NDC Oslo 2019David Wengier
 
첫 리액트 경험기
첫 리액트 경험기첫 리액트 경험기
첫 리액트 경험기석진 고
 
Leveraging volunteer talent for organizational change
Leveraging volunteer talent for organizational changeLeveraging volunteer talent for organizational change
Leveraging volunteer talent for organizational changeMelissa Miller
 
A (very) opinionated guide to MSBuild and Project Files
A (very) opinionated guide to MSBuild and Project FilesA (very) opinionated guide to MSBuild and Project Files
A (very) opinionated guide to MSBuild and Project FilesDavid Wengier
 
Designing The Right Schema To Power Heap (PGConf Silicon Valley 2016)
Designing The Right Schema To Power Heap (PGConf Silicon Valley 2016)Designing The Right Schema To Power Heap (PGConf Silicon Valley 2016)
Designing The Right Schema To Power Heap (PGConf Silicon Valley 2016)Dan Robinson
 
Automated%20testing%20with%20Espresso2.x
Automated%20testing%20with%20Espresso2.xAutomated%20testing%20with%20Espresso2.x
Automated%20testing%20with%20Espresso2.xTatsuya Maki
 
Workboxで始める Service Worker
Workboxで始める Service WorkerWorkboxで始める Service Worker
Workboxで始める Service WorkerKazuyoshi Tsuchiya
 
No More Deadlocks; Asynchronous Programming in .NET
No More Deadlocks; Asynchronous Programming in .NETNo More Deadlocks; Asynchronous Programming in .NET
No More Deadlocks; Asynchronous Programming in .NETFilip Ekberg
 

What's hot (20)

Provisioning & Migration with p2: Case study - The Good, the Bad and the Ugly
Provisioning & Migration with p2: Case study - The Good, the Bad and the UglyProvisioning & Migration with p2: Case study - The Good, the Bad and the Ugly
Provisioning & Migration with p2: Case study - The Good, the Bad and the Ugly
 
Redux. From twitter hype to production
Redux. From twitter hype to productionRedux. From twitter hype to production
Redux. From twitter hype to production
 
The Ring programming language version 1.10 book - Part 82 of 212
The Ring programming language version 1.10 book - Part 82 of 212The Ring programming language version 1.10 book - Part 82 of 212
The Ring programming language version 1.10 book - Part 82 of 212
 
[Android] PLAYING WITH FRAGMENT
[Android] PLAYING WITH FRAGMENT[Android] PLAYING WITH FRAGMENT
[Android] PLAYING WITH FRAGMENT
 
Introduction to Angular js
Introduction to Angular jsIntroduction to Angular js
Introduction to Angular js
 
Kitchen Design Guide - Consumer Reports
Kitchen Design Guide - Consumer ReportsKitchen Design Guide - Consumer Reports
Kitchen Design Guide - Consumer Reports
 
View controller life cycle
View controller life cycleView controller life cycle
View controller life cycle
 
Asynchronous CompletableFuture Presentation by László-Róbert Albert @Crossover
Asynchronous CompletableFuture Presentation by László-Róbert Albert @CrossoverAsynchronous CompletableFuture Presentation by László-Róbert Albert @Crossover
Asynchronous CompletableFuture Presentation by László-Róbert Albert @Crossover
 
Firebase ng2 zurich
Firebase ng2 zurichFirebase ng2 zurich
Firebase ng2 zurich
 
Lowering in C#: What really happens with your code?, from NDC Oslo 2019
Lowering in C#: What really happens with your code?, from NDC Oslo 2019Lowering in C#: What really happens with your code?, from NDC Oslo 2019
Lowering in C#: What really happens with your code?, from NDC Oslo 2019
 
첫 리액트 경험기
첫 리액트 경험기첫 리액트 경험기
첫 리액트 경험기
 
Granada_Perl_Workshop_2014_Google_API_Client
Granada_Perl_Workshop_2014_Google_API_ClientGranada_Perl_Workshop_2014_Google_API_Client
Granada_Perl_Workshop_2014_Google_API_Client
 
Leveraging volunteer talent for organizational change
Leveraging volunteer talent for organizational changeLeveraging volunteer talent for organizational change
Leveraging volunteer talent for organizational change
 
A (very) opinionated guide to MSBuild and Project Files
A (very) opinionated guide to MSBuild and Project FilesA (very) opinionated guide to MSBuild and Project Files
A (very) opinionated guide to MSBuild and Project Files
 
Designing The Right Schema To Power Heap (PGConf Silicon Valley 2016)
Designing The Right Schema To Power Heap (PGConf Silicon Valley 2016)Designing The Right Schema To Power Heap (PGConf Silicon Valley 2016)
Designing The Right Schema To Power Heap (PGConf Silicon Valley 2016)
 
Rxjs marble-testing
Rxjs marble-testingRxjs marble-testing
Rxjs marble-testing
 
React 101
React 101React 101
React 101
 
Automated%20testing%20with%20Espresso2.x
Automated%20testing%20with%20Espresso2.xAutomated%20testing%20with%20Espresso2.x
Automated%20testing%20with%20Espresso2.x
 
Workboxで始める Service Worker
Workboxで始める Service WorkerWorkboxで始める Service Worker
Workboxで始める Service Worker
 
No More Deadlocks; Asynchronous Programming in .NET
No More Deadlocks; Asynchronous Programming in .NETNo More Deadlocks; Asynchronous Programming in .NET
No More Deadlocks; Asynchronous Programming in .NET
 

Similar to Steam Learn: Asynchronous Javascript

MeasureCamp IX (London) - 10 JavaScript Concepts for web analysts
MeasureCamp IX (London) - 10 JavaScript Concepts for web analystsMeasureCamp IX (London) - 10 JavaScript Concepts for web analysts
MeasureCamp IX (London) - 10 JavaScript Concepts for web analystsSimo Ahava
 
Ditching JQuery
Ditching JQueryDitching JQuery
Ditching JQueryhowlowck
 
Multi Client Development with Spring - Josh Long
Multi Client Development with Spring - Josh Long Multi Client Development with Spring - Josh Long
Multi Client Development with Spring - Josh Long jaxconf
 
Reactive Java Microservices with Spring Boot and JHipster - Denver JUG 2021
Reactive Java Microservices with Spring Boot and JHipster - Denver JUG 2021Reactive Java Microservices with Spring Boot and JHipster - Denver JUG 2021
Reactive Java Microservices with Spring Boot and JHipster - Denver JUG 2021Matt Raible
 
Android Best Practices
Android Best PracticesAndroid Best Practices
Android Best PracticesYekmer Simsek
 
Visual Testing: Turbo-Charge Your Functional Tests with Visual Powers in Just...
Visual Testing: Turbo-Charge Your Functional Tests with Visual Powers in Just...Visual Testing: Turbo-Charge Your Functional Tests with Visual Powers in Just...
Visual Testing: Turbo-Charge Your Functional Tests with Visual Powers in Just...Applitools
 
Angular directive filter and routing
Angular directive filter and routingAngular directive filter and routing
Angular directive filter and routingjagriti srivastava
 
Ten useful JavaScript tips & best practices
Ten useful JavaScript tips & best practicesTen useful JavaScript tips & best practices
Ten useful JavaScript tips & best practicesAnkit Rastogi
 
The Promised Land (in Angular)
The Promised Land (in Angular)The Promised Land (in Angular)
The Promised Land (in Angular)Domenic Denicola
 
JavaScript Functions
JavaScript FunctionsJavaScript Functions
JavaScript FunctionsColin DeCarlo
 
Week 8
Week 8Week 8
Week 8A VD
 
MCC Scripts update
MCC Scripts updateMCC Scripts update
MCC Scripts updatesupergigas
 
Async js - Nemetschek Presentaion @ HackBulgaria
Async js - Nemetschek Presentaion @ HackBulgariaAsync js - Nemetschek Presentaion @ HackBulgaria
Async js - Nemetschek Presentaion @ HackBulgariaHackBulgaria
 
20150516 modern web_conf_tw
20150516 modern web_conf_tw20150516 modern web_conf_tw
20150516 modern web_conf_twTse-Ching Ho
 
Achievement Unlocked: Drive development, increase velocity, and write blissfu...
Achievement Unlocked: Drive development, increase velocity, and write blissfu...Achievement Unlocked: Drive development, increase velocity, and write blissfu...
Achievement Unlocked: Drive development, increase velocity, and write blissfu...All Things Open
 
Future of Web Apps: Google Gears
Future of Web Apps: Google GearsFuture of Web Apps: Google Gears
Future of Web Apps: Google Gearsdion
 
Progressive Enhancment with Rails and React
Progressive Enhancment with Rails and ReactProgressive Enhancment with Rails and React
Progressive Enhancment with Rails and ReactTyler Johnston
 
Adding a modern twist to legacy web applications
Adding a modern twist to legacy web applicationsAdding a modern twist to legacy web applications
Adding a modern twist to legacy web applicationsJeff Durta
 

Similar to Steam Learn: Asynchronous Javascript (20)

MeasureCamp IX (London) - 10 JavaScript Concepts for web analysts
MeasureCamp IX (London) - 10 JavaScript Concepts for web analystsMeasureCamp IX (London) - 10 JavaScript Concepts for web analysts
MeasureCamp IX (London) - 10 JavaScript Concepts for web analysts
 
Ditching JQuery
Ditching JQueryDitching JQuery
Ditching JQuery
 
Multi Client Development with Spring - Josh Long
Multi Client Development with Spring - Josh Long Multi Client Development with Spring - Josh Long
Multi Client Development with Spring - Josh Long
 
Reactive Java Microservices with Spring Boot and JHipster - Denver JUG 2021
Reactive Java Microservices with Spring Boot and JHipster - Denver JUG 2021Reactive Java Microservices with Spring Boot and JHipster - Denver JUG 2021
Reactive Java Microservices with Spring Boot and JHipster - Denver JUG 2021
 
Android Best Practices
Android Best PracticesAndroid Best Practices
Android Best Practices
 
Visual Testing: Turbo-Charge Your Functional Tests with Visual Powers in Just...
Visual Testing: Turbo-Charge Your Functional Tests with Visual Powers in Just...Visual Testing: Turbo-Charge Your Functional Tests with Visual Powers in Just...
Visual Testing: Turbo-Charge Your Functional Tests with Visual Powers in Just...
 
Angular Workshop_Sarajevo2
Angular Workshop_Sarajevo2Angular Workshop_Sarajevo2
Angular Workshop_Sarajevo2
 
Angular directive filter and routing
Angular directive filter and routingAngular directive filter and routing
Angular directive filter and routing
 
Sane Async Patterns
Sane Async PatternsSane Async Patterns
Sane Async Patterns
 
Ten useful JavaScript tips & best practices
Ten useful JavaScript tips & best practicesTen useful JavaScript tips & best practices
Ten useful JavaScript tips & best practices
 
The Promised Land (in Angular)
The Promised Land (in Angular)The Promised Land (in Angular)
The Promised Land (in Angular)
 
JavaScript Functions
JavaScript FunctionsJavaScript Functions
JavaScript Functions
 
Week 8
Week 8Week 8
Week 8
 
MCC Scripts update
MCC Scripts updateMCC Scripts update
MCC Scripts update
 
Async js - Nemetschek Presentaion @ HackBulgaria
Async js - Nemetschek Presentaion @ HackBulgariaAsync js - Nemetschek Presentaion @ HackBulgaria
Async js - Nemetschek Presentaion @ HackBulgaria
 
20150516 modern web_conf_tw
20150516 modern web_conf_tw20150516 modern web_conf_tw
20150516 modern web_conf_tw
 
Achievement Unlocked: Drive development, increase velocity, and write blissfu...
Achievement Unlocked: Drive development, increase velocity, and write blissfu...Achievement Unlocked: Drive development, increase velocity, and write blissfu...
Achievement Unlocked: Drive development, increase velocity, and write blissfu...
 
Future of Web Apps: Google Gears
Future of Web Apps: Google GearsFuture of Web Apps: Google Gears
Future of Web Apps: Google Gears
 
Progressive Enhancment with Rails and React
Progressive Enhancment with Rails and ReactProgressive Enhancment with Rails and React
Progressive Enhancment with Rails and React
 
Adding a modern twist to legacy web applications
Adding a modern twist to legacy web applicationsAdding a modern twist to legacy web applications
Adding a modern twist to legacy web applications
 

More from inovia

10 tips for Redux at scale
10 tips for Redux at scale10 tips for Redux at scale
10 tips for Redux at scaleinovia
 
10 essentials steps for kafka streaming services
10 essentials steps for kafka streaming services10 essentials steps for kafka streaming services
10 essentials steps for kafka streaming servicesinovia
 
Redux at scale
Redux at scaleRedux at scale
Redux at scaleinovia
 
DocuSign's Road to react
DocuSign's Road to reactDocuSign's Road to react
DocuSign's Road to reactinovia
 
API Gateway: Nginx way
API Gateway: Nginx wayAPI Gateway: Nginx way
API Gateway: Nginx wayinovia
 
Kafka: meetup microservice
Kafka: meetup microserviceKafka: meetup microservice
Kafka: meetup microserviceinovia
 
Microservice: starting point
Microservice:  starting pointMicroservice:  starting point
Microservice: starting pointinovia
 
Correlation id (tid)
Correlation id (tid)Correlation id (tid)
Correlation id (tid)inovia
 
Meetic back end redesign - Meetup microservices
Meetic back end redesign - Meetup microservicesMeetic back end redesign - Meetup microservices
Meetic back end redesign - Meetup microservicesinovia
 
Security in microservices architectures
Security in microservices architecturesSecurity in microservices architectures
Security in microservices architecturesinovia
 
Building a Secure, Performant Network Fabric for Microservice Applications
Building a Secure, Performant Network Fabric for Microservice ApplicationsBuilding a Secure, Performant Network Fabric for Microservice Applications
Building a Secure, Performant Network Fabric for Microservice Applicationsinovia
 
Microservices vs SOA
Microservices vs SOAMicroservices vs SOA
Microservices vs SOAinovia
 
CQRS, an introduction by JC Bohin
CQRS, an introduction by JC BohinCQRS, an introduction by JC Bohin
CQRS, an introduction by JC Bohininovia
 
Domain Driven Design
Domain Driven DesignDomain Driven Design
Domain Driven Designinovia
 
Oauth2, open-id connect with microservices
Oauth2, open-id connect with microservicesOauth2, open-id connect with microservices
Oauth2, open-id connect with microservicesinovia
 
You probably don't need microservices
You probably don't need microservicesYou probably don't need microservices
You probably don't need microservicesinovia
 
Api Gateway - What's the use of an api gateway?
Api Gateway - What's the use of an api gateway?Api Gateway - What's the use of an api gateway?
Api Gateway - What's the use of an api gateway?inovia
 
Steam Learn: An introduction to Redis
Steam Learn: An introduction to RedisSteam Learn: An introduction to Redis
Steam Learn: An introduction to Redisinovia
 
Steam Learn: Speedrun et TAS
Steam Learn: Speedrun et TASSteam Learn: Speedrun et TAS
Steam Learn: Speedrun et TASinovia
 
Steam Learn: Cheat sheet for Vim
Steam Learn: Cheat sheet for VimSteam Learn: Cheat sheet for Vim
Steam Learn: Cheat sheet for Viminovia
 

More from inovia (20)

10 tips for Redux at scale
10 tips for Redux at scale10 tips for Redux at scale
10 tips for Redux at scale
 
10 essentials steps for kafka streaming services
10 essentials steps for kafka streaming services10 essentials steps for kafka streaming services
10 essentials steps for kafka streaming services
 
Redux at scale
Redux at scaleRedux at scale
Redux at scale
 
DocuSign's Road to react
DocuSign's Road to reactDocuSign's Road to react
DocuSign's Road to react
 
API Gateway: Nginx way
API Gateway: Nginx wayAPI Gateway: Nginx way
API Gateway: Nginx way
 
Kafka: meetup microservice
Kafka: meetup microserviceKafka: meetup microservice
Kafka: meetup microservice
 
Microservice: starting point
Microservice:  starting pointMicroservice:  starting point
Microservice: starting point
 
Correlation id (tid)
Correlation id (tid)Correlation id (tid)
Correlation id (tid)
 
Meetic back end redesign - Meetup microservices
Meetic back end redesign - Meetup microservicesMeetic back end redesign - Meetup microservices
Meetic back end redesign - Meetup microservices
 
Security in microservices architectures
Security in microservices architecturesSecurity in microservices architectures
Security in microservices architectures
 
Building a Secure, Performant Network Fabric for Microservice Applications
Building a Secure, Performant Network Fabric for Microservice ApplicationsBuilding a Secure, Performant Network Fabric for Microservice Applications
Building a Secure, Performant Network Fabric for Microservice Applications
 
Microservices vs SOA
Microservices vs SOAMicroservices vs SOA
Microservices vs SOA
 
CQRS, an introduction by JC Bohin
CQRS, an introduction by JC BohinCQRS, an introduction by JC Bohin
CQRS, an introduction by JC Bohin
 
Domain Driven Design
Domain Driven DesignDomain Driven Design
Domain Driven Design
 
Oauth2, open-id connect with microservices
Oauth2, open-id connect with microservicesOauth2, open-id connect with microservices
Oauth2, open-id connect with microservices
 
You probably don't need microservices
You probably don't need microservicesYou probably don't need microservices
You probably don't need microservices
 
Api Gateway - What's the use of an api gateway?
Api Gateway - What's the use of an api gateway?Api Gateway - What's the use of an api gateway?
Api Gateway - What's the use of an api gateway?
 
Steam Learn: An introduction to Redis
Steam Learn: An introduction to RedisSteam Learn: An introduction to Redis
Steam Learn: An introduction to Redis
 
Steam Learn: Speedrun et TAS
Steam Learn: Speedrun et TASSteam Learn: Speedrun et TAS
Steam Learn: Speedrun et TAS
 
Steam Learn: Cheat sheet for Vim
Steam Learn: Cheat sheet for VimSteam Learn: Cheat sheet for Vim
Steam Learn: Cheat sheet for Vim
 

Recently uploaded

ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....kzayra69
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Hr365.us smith
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesŁukasz Chruściel
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)jennyeacort
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 

Recently uploaded (20)

ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New Features
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 

Steam Learn: Asynchronous Javascript

  • 1. 6th of June, 2015 Asynchronous Javascript Common and useful patterns by Steven Rémot
  • 2. 6th of June, 2015 Table of contents 1. Callbacks 2. Promises 3. Generators
  • 3. 6th of June, 2015 Table of contents 1. Callbacks 2. Promises 3. Generators
  • 4. 6th of June, 2015 Callbacks - Usage function GameController() { var dirChangedCb = function () {}; this.onDirectionChanged = function (callback) { dirChangedCb = callback; }; document.addEventListener('keydown', function (event) { dirChangedCb(determineEventDirection(event)); }); } var gc = new GameController(); gc.onDirectionChanged(function (direction) { hero.move(direction); });
  • 5. 6th of June, 2015 Callbacks - Avoiding conflicts function GameController() { var dirChangedCb = function () {}; this.onDirectionChanged = function (callback) { dirChangedCb = callback; }; document.addEventListener('keydown', function (event) { dirChangedCb(determineEventDirection(event)); }); } var gc = new GameController(); gc.onDirectionChanged(function (direction) { hero.move(direction); }); gc.onDirectionChanged(function (direction) { enemy.reactTo(direction); }); Only one callback is saved
  • 6. 6th of June, 2015 Callbacks - Avoiding conflicts function GameController() { var dirChangedCbs = []; this.onDirectionChanged = function (callback) { dirChangedCbs.push(callback); }; document.addEventListener('keydown', function (event) { for (var i = 0; i < dirChangedCbs.length; i++) { dirChangedCbs[i](determineEventDirection(event)); } }); } var gc = new GameController(); gc.onDirectionChanged(function (direction) { hero.move(direction); }); gc.onDirectionChanged(function (direction) { enemy.reactTo(direction); });
  • 7. 6th of June, 2015 Callbacks - Nested operations function loadHero(loadingFinishedCallback) { http.get('/characters/hero.json', function (heroData) { loadingFinishedCallback({ data: heroData }); }); }
  • 8. 6th of June, 2015 Callbacks - Nested operations function loadHero(loadingFinishedCallback) { http.get('/characters/hero.json', function (heroData) { http.get(heroData.modelUrl, function (model) { loadingFinishedCallback({ data: heroData, model: model }); }); }); }
  • 9. 6th of June, 2015 Callbacks - Nested operations function loadHero(loadingFinishedCallback) { http.get('/characters/hero.json', function (heroData) { http.get(heroData.modelUrl, function (model) { http.get(model.materialUrl, function (material) { loadingFinishedCallback({ data: heroData, model: model, material: material }); }); }); }); }
  • 10. 6th of June, 2015 Callbacks - Nested operations function loadHero(loadingFinishedCallback) { http.get('/characters/hero.json', function (heroData) { loadGraphics(heroData.modelUrl, function (graphics) { loadingFinishedCallback({ data: heroData, model: graphics.model, material: graphics.material }); }); }); }
  • 11. 6th of June, 2015 Callbacks - Limits ● Nested callbacks are not handy ● Even worse with error catching ● Waiting for multiple callbacks is hard Callbacks are bad for async operations
  • 12. 6th of June, 2015 Table of contents 1. Callbacks 2. Promises 3. Generators
  • 13. 6th of June, 2015 Promises - Basics function httpGet(url) { return new Promise(function (resolve) { http.get(url, function (data) { resolve(data); }); }); }
  • 14. 6th of June, 2015 Promises - Basics function httpGet(url) { return new Promise(function (resolve) { http.get(url, resolve); }); }
  • 15. 6th of June, 2015 Promises - Basics function httpGet(url) { return new Promise(function (resolve, reject) { http.get(url, resolve, reject); }); }
  • 16. 6th of June, 2015 Promises - Chaining function loadHero() { return httpGet('/characters/hero.json') .then(function (heroData) { return { data: heroData }; }); } loadHero().then(function (hero) { console.log(hero.data); });
  • 17. 6th of June, 2015 Promises - Chaining function loadHero() { return httpGet('/characters/hero.json') .then(function (heroData) { return httpGet(heroData.modelUrl).then(function (model) { return { data: heroData, model: model }; }); }); } loadHero().then(function (hero) { console.log(hero.data); console.log(hero.model); });
  • 18. 6th of June, 2015 Promises - Chaining function loadHero() { var hero = {}; return httpGet('/characters/hero.json') .then(function (heroData) { hero.data = heroData; return httpGet(heroData.modelUrl); }) .then(function (model) { hero.model = model; return hero; }); } loadHero().then(function (hero) { console.log(hero.data); console.log(hero.model); });
  • 19. 6th of June, 2015 Promises - Chaining function loadHero() { var hero = {}; return httpGet('/characters/hero.json') .then(function (heroData) { hero.data = heroData; return httpGet(heroData.modelUrl); }) .then(function (model) { hero.model = model; return httpGet(model.materialUrl); }) .then(function (material) { hero.material = material; return hero; }); }
  • 20. 6th of June, 2015 Promises - Chaining function loadHero() { var hero = {}; return httpGet('/characters/hero.json') .then(function (heroData) { hero.data = heroData; return httpGet(heroData.modelUrl); }) .then(function (model) { hero.model = model; return httpGet(model.materialUrl); }) .then(function (material) { hero.material = material; return hero; }) .catch(function (error) { console.log(error); return null; });
  • 21. 6th of June, 2015 Promises - Waiting all promises function loadObjects() { return Promise.all([ loadHero(), loadEnemy(), loadDoor(), loadWall(), // ... ]); } loadObjects().then(function (objects) { var hero = objects[0]; var enemy = objects[1]; // ... });
  • 22. 6th of June, 2015 Promises - How to get them ● In Ecmascript 6 standard library ● Available through polyfills: https://github.com/jakearchibald/es6-promise ● Alternative APIs: https://github.com/kriskowal/q https://github.com/petkaantonov/bluebird
  • 23. 6th of June, 2015 Promises Nice, but… ● Verbose ● Still writing in an asynchronous way We can do better!
  • 24. 6th of June, 2015 Table of contents 1. Callbacks 2. Promises 3. Generators
  • 25. 6th of June, 2015 Generator - Basics function* counter() { for (var i = 0; i < 10; i++) { yield i; } } var count = counter(); console.log(count.next()); // 0 console.log(count.next()); // 1 // ...
  • 26. 6th of June, 2015 Generator - Basics function* loadHero() { var hero = {}; hero.data = yield httpGet('/characters/hero.json'); hero.model = yield httpGet(hero.data.modelUrl); hero.material = yield httpGet(hero.model.materialUrl); return hero; } spawn(loadHero).then(function (hero) { console.log(hero); // { data: <...>, model: <...>, ... } });
  • 27. 6th of June, 2015 Generator - Basics function* loadHero() { var hero = {}; try { hero.data = yield httpGet('/characters/hero.json'); hero.model = yield httpGet(hero.data.modelUrl); hero.material = yield httpGet(hero.model.materialUrl); } catch (error) { console.log(error); hero = null; } return hero; } spawn(loadHero).then(function (hero) { console.log(hero); // { data: <...>, model: <...>, ... } });
  • 28. 6th of June, 2015 Generator - Basics async function loadHero() { var hero = {}; try { hero.data = await httpGet('/characters/hero.json'); hero.model = await httpGet(hero.data.modelUrl); hero.material = await httpGet(hero.model.materialUrl); } catch (error) { console.log(error); hero = null; } return hero; } loadHero().then(function () { console.log(hero); // { data: <...>, model: <...>, ... } });
  • 29. 6th of June, 2015 Generator - Browser support ● Generator are ES6 ● Async functions are ES7 ● Use them today with transpilers: https://github.com/google/traceur-compiler https://babeljs.io/
  • 30. 6th of June, 2015 Thanks for listening! References: https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Promise https://www.promisejs.org/ https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Instructions/function* https://github.com/lukehoban/ecmascript-asyncawait
  • 31. 6th of June, 2015 Join the community ! (in Paris) Social networks : ● Follow us on Twitter : https://twitter.com/steamlearn ● Like us on Facebook : https://www.facebook.com/steamlearn SteamLearn is an Inovia initiative : inovia.fr You wish to be in the audience ? Join the meetup group! http://www.meetup.com/Steam-Learn/