Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
Thenez vos promesses
Search
Deyine
June 24, 2018
Programming
0
120
Thenez vos promesses
Dans cette présentation, on fait le tour de l'evolution de la programmation asyncrone en JS
Deyine
June 24, 2018
Tweet
Share
More Decks by Deyine
See All by Deyine
Android development flow
deyine
3
130
MVP architecture
deyine
2
84
Other Decks in Programming
See All in Programming
毎日13時間もかかるバッチ処理をたった3日で60%短縮するためにやったこと
sho_ssk_
1
550
20241217 競争力強化とビジネス価値創出への挑戦:モノタロウのシステムモダナイズ、開発組織の進化と今後の展望
monotaro
PRO
0
290
自分ひとりから始められる生産性向上の取り組み #でぃーぷらすオオサカ
irof
3
360
Rubyでつくるパケットキャプチャツール
ydah
0
180
DevFest - Serverless 101 with Google Cloud Functions
tunmise
0
140
Внедряем бюджетирование, или Как сделать хорошо?
lamodatech
0
950
ATDDで素早く安定した デリバリを実現しよう!
tonnsama
1
1.9k
最近のVS Codeで気になるニュース 2025/01
74th
1
110
Fibonacci Function Gallery - Part 2
philipschwarz
PRO
0
210
functionalなアプローチで動的要素を排除する
ryopeko
1
220
Асинхронность неизбежна: как мы проектировали сервис уведомлений
lamodatech
0
1.4k
AppRouterを用いた大規模サービス開発におけるディレクトリ構成の変遷と問題点
eiganken
1
450
Featured
See All Featured
Reflections from 52 weeks, 52 projects
jeffersonlam
348
20k
Bash Introduction
62gerente
610
210k
Dealing with People You Can't Stand - Big Design 2015
cassininazir
365
25k
Documentation Writing (for coders)
carmenintech
67
4.5k
The World Runs on Bad Software
bkeepers
PRO
66
11k
Building a Scalable Design System with Sketch
lauravandoore
460
33k
Mobile First: as difficult as doing things right
swwweet
222
9k
Docker and Python
trallard
43
3.2k
Build your cross-platform service in a week with App Engine
jlugia
229
18k
How to Ace a Technical Interview
jacobian
276
23k
What's in a price? How to price your products and services
michaelherold
244
12k
Adopting Sorbet at Scale
ufuk
74
9.2k
Transcript
THENEZ VOS PROMISES DEYINE JIDDOU Presented by:
THENEZ VOS PROMISES 2
THENEZ VOS PROMISES 3 La plupart du temps on écrit
du code synchrone AKA BLOCKING
THENEZ VOS PROMISES 4
THENEZ VOS PROMISES 5 Traitements lourds, difficile à optimiser MULTI-THREADING
THREAD POOL BACKGROUND WORKER INVOKE KILL/PAUSE ERROR HANDLING RETRY WAIT
THENEZ VOS PROMISES 6 En JAVASCRIPT, on fait les choses
différemment
THENEZ VOS PROMISES 7 Un seul Thread en Javascript
THENEZ VOS PROMISES 8 console.log(1); setTimeout(function() { console.log('Finished'); }, 10);
console.log(2); console.log(3); console.log(4);
THENEZ VOS PROMISES 9 The Event loop CALL STACK console.log(1)
THENEZ VOS PROMISES 10 The Event loop CALL STACK setTimeout
THENEZ VOS PROMISES 11 The Event loop CALL STACK setTimeout
BROWSER DOM Events XHR(Ajax) Timers …
THENEZ VOS PROMISES 12 The Event loop CALL STACK setTimeout
BROWSER DOM Events XHR(Ajax) Timers … console.log(2) …
THENEZ VOS PROMISES 13 The Event loop CALL STACK setTimeout
BROWSER DOM Events XHR(Ajax) Timers … console.log(2) … EVENT QUEUE Function1
THENEZ VOS PROMISES 14 The Event loop CALL STACK setTimeout
BROWSER DOM Events XHR(Ajax) Timers … console.log(2) … EVENT QUEUE Function1
THENEZ VOS PROMISES 15
THENEZ VOS PROMISES 16 function getMeetup() { var meetup; $.get('/meetup',
function(data) { meetup = data; }); return meetup; } var JsMeetup = getMeetup(); console.log(JsMeetup); // null
THENEZ VOS PROMISES 17 Traiter le résultat au moment de
la récupération
THENEZ VOS PROMISES 18 function getMeetup(callback) { $.get('/meetup', function(data) {
callback(data); }); } var JsMeetup = getMeetup(function(meetup) { console.log(JsMeetup); // Object });
THENEZ VOS PROMISES 19 function getMeetup(callback) { $.get('/meetup', function(data) {
$.get('/members', function(response) { callback(data); }); }); } var JsMeetup = getMeetup(function(meetup) { console.log(JsMeetup); // Object });
THENEZ VOS PROMISES 20 CALLBACK HELL
THENEZ VOS PROMISES 21 SPAGHETTI var JsMeetup = null; var
members = null; var finished = 0; function getMeetup() { $.get('/meetup', function(data) { JsMeetup = data; finished++; }); } function getMembers() { $.get('/members', function(data) { members = data; finished++; }); } getMeetup(); getMembers(); while (true) { if(finished == 2) { console.log(JsMeetup); // Object console.log(members); // Object break; }
THENEZ VOS PROMISES 22 Vous pouvez écrire une petite librairie
pour simplifier
THENEZ VOS PROMISES 23 En réalité beaucoup l’ont fait
THENEZ VOS PROMISES 24 PROMISES
THENEZ VOS PROMISES 25 Promise est tout simplement un OBJET
Représente le résultat de l’execution d’une fonction 3 états possibles • pending • fulfilled • rejected Supporté nativement Then-able
THENEZ VOS PROMISES 26 function getMeetup() { var task =
$.Deferred(); $.get('/meetup', function(data) { task.resolve(data); }, function(err) { task.reject(err); }); return task.promise(); } var JsMeetup = getMeetup() .then(function(data) { console.log(JsMeetup); });
THENEZ VOS PROMISES 27 function getMembers(meetup) { var task =
$.Deferred(); $.get(‘/meetup/' + meetup.id + '/members', function(data) { task.resolve(data); }, function(err) { task.reject(err); }); return task.promise(); } var JsMeetup = getMeetup() .then(function(data) { return getMembers(data) }) .then(function(result) { console.log(result); }); Chaining
THENEZ VOS PROMISES 28 function getMembers(meetup) { var task =
$.Deferred(); $.get(‘/meetup/' + meetup.id + '/members', function(data) { task.resolve(data); }, function(err) { task.reject(err); }); return task.promise(); } var JsMeetup = getMeetup() .then((data) => { return getMembers(data) }) .then((result) => { console.log(result); }); Chaining
THENEZ VOS PROMISES 29 function getMembers(meetup) { var task =
$.Deferred(); $.get(‘/meetup/' + meetup.id + '/members', function(data) { task.resolve(data); }, function(err) { task.reject(err); }); return task.promise(); } var JsMeetup = getMeetup() .then(data => getMembers(data)) .then(result => console.log(result)); Chaining
THENEZ VOS PROMISES 30 function getMembers(meetup) { var task =
$.Deferred(); $.get(‘/meetup/' + meetup.id + '/members', function(data) { task.resolve(data); }, function(err) { task.reject(err); }); return task.promise(); } var JsMeetup = getMeetup() .then(getMembers) .then(console.log); Chaining
THENEZ VOS PROMISES 31 function getMembers(dateMeetup, meetup) { var task
= $.Deferred(); $.get(‘/meetup/' + meetup.id + '/members', function(data) { task.resolve(data); }, function(err) { task.reject(err); }); return task.promise(); } var JsMeetup = getMeetup() .then(data => getMembers.bind(new Date(), data)) .then(console.log); Chaining
THENEZ VOS PROMISES 32 var JsMeetup = getMeetup() .then(data =>
getMembers(data)) .then(result => console.log(result)) .catch(err => { console.log('And error occured during data fetching'); }); Error handling
THENEZ VOS PROMISES 33 var JsMeetup = getMeetup() .then(data =>
{ if(!data || data.length == 0){ throw new Error('No meetup found'); } return getMembers(data); }) .then(result => console.log(result)) .catch(err => { console.log('And error occured during data fetching' + err); }); Error handling
THENEZ VOS PROMISES 34 var JsMeetup = getMeetup() .then(data =>
{ if(!data || data.length == 0){ throw new Error('No meetup found'); } return getMembers(data); }) .then(result => console.log(result)) .catch(err => { console.log('And error occured during data fetching' + err); }); Try / Catch / Finally
THENEZ VOS PROMISES 35 PROMISES
THENEZ VOS PROMISES 36 PROMISES ES7 - couche au dessus
des Promises
THENEZ VOS PROMISES 37 var config; return SmsConfig.find() .exec() .then(selectMatchedConfig.bind(null,
sms)) // Ordre des params .then(c => { config = c; // Réutilisation d’un résultat return extractValues(sms, config); }) .then(vals => { prepareDetectorParams(vals); return updateTransaction(sms, config, vals); }); PROMISE HELL
THENEZ VOS PROMISES 38 async function getMeetup() { var task
= $.Deferred(); $.get('/meetup', function(data) { task.resolve(data); }, function(err) { task.reject(err); }); return task.promise(); } async function getMembers(meetup) { var task = $.Deferred(); $.get('/meetup/' + meetup.id + '/members', function(data) { task.resolve(data); }, function(err) { task.reject(err); }); ASYNC / AWAIT
THENEZ VOS PROMISES 39 (async () => { try {
startSpinner(); var meetup = await getMeetup(); var members = await getMembers(meetup); console.log(meetup); stopSpinner(); } catch(err) { displayError(); } })() ASYNC / AWAIT
THENEZ VOS PROMISES 40 ASYNC / AWAIT HELL AWAIT AWAIT
AWAIT AWAIT AWAIT
THENEZ VOS PROMISES 41 Parallèle Await uniquement si le résultat
d’une fonction est utile Regrouper les Await lié Promise.all
THANK YOU!