Zenika Academy
Coder l'asynchrone en JavaScript
By Matthieu Lux
Coder l'asynchrone n'est pas facile
Synchrone
const oAuthResponse = syncRequest(oAuthOptions());
const token = JSON.parse(oAuthResponse.body).access_token;
const searchResponse = syncRequest(searchOptions(token));
const search = JSON.parse(searchResponse.body);
search.statuses.forEach(status => console.log(status.text));
Simple mais inutilisable et contre performant
On utilise alors les callbacks pour passer à l'asynchrone
Callbacks
callbackRequest(oAuthOptions(), (error, response, body) => {
const token = JSON.parse(body).access_token;
callbackRequest(searchOptions(token), (error, response, body) => {
const search = JSON.parse(body);
search.statuses.forEach(status => console.log(status.text));
});
});
L'utilisation importante des callbacks crée un code complexe
Comment avoir du code asynchrone maintenable ?
Les promesses
Promesses
promiseRequest(oAuthOptions()).then(response => {
const token = JSON.parse(response).access_token;
return promiseRequest(searchOptions(token));
}).then(response => {
const search = JSON.parse(response);
search.statuses.forEach(status => console.log(status.text));
});
On peut aller encore plus loin
ES6 incoming
Generators
function *foo() {
yield 1;
yield 2;
yield 3;
}
var it = foo();
console.log( it.next() ); // { value:1, done:false }
console.log( it.next() ); // { value:2, done:false }
console.log( it.next() ); // { value:3, done:false }
console.log( it.next() ); // { value: undefined, done: true }
Et si on yield une promesse ?
Generators
import co from 'co';
co(function *() {
const oAuthResponse = yield promiseRequest(oAuthOptions());
const token = JSON.parse(oAuthResponse).access_token;
const searchResponse = yield promiseRequest(searchOptions(token));
const search = JSON.parse(searchResponse);
search.statuses.forEach(status => console.log(status.text));
});
Peut-on aller encore plus loin ?
ES7 incoming
Async
async function start() {
const oAuthResponse = await promiseRequest(oAuthOptions());
const token = JSON.parse(oAuthResponse).access_token;
const searchResponse = await promiseRequest(searchOptions(token));
const search = JSON.parse(searchResponse);
search.statuses.forEach(status => console.log(status.text));
}
start();
Coder l'asynchrone en JavaScript
Matthieu Lux (@Swiip)