Hao-kang Den <github @hden>
Harnessing asynchronicity - callbacks, promises, generators, and coroutines
Agenda
● Why asynchronous?
● Callback
● Promise
● Generator [--harmony]
● Coroutines [--harmony]
Why asynchronous?Callbacks
Original slides introducing node.js by Ryan Dahl @jsconf 2009
@ry
@ry
@ry
@ry
@ry
@ry
@ry
@ry
@ry
@ry
@ry
@ry
@ry
@ry
Pyramid of Doomstep1(function (value1) {
step2(value1, function(value2) {
step3(value2, function(value3) {
step4(value3, function(value4) {
// Do something with value4
});
});
});
});
Hairball
Promise/A+Q.fcall(promisedStep1)
.then(promisedStep2)
.then(promisedStep3)
.then(promisedStep4)
.then(function (value4) {
// Do something with value4
})
.catch(function (error) {
// Handle any error from all above steps
})
.done(); https://github.com/kriskowal/q
ECMAScript a.k.a. JavaScript
● version 1 - June 1997● version 2 - June 1998● version 3 - December 1999● version 4 - Abandoned● version 5 - December 2009● version 5.1 - June 2011● version 6 - [Harmony] Work in progress
Generatorsfunction* fibonacci() {
let [prev, curr] = [0, 1];
for (;;) {
[prev, curr] = [curr, prev + curr];
yield curr;
}
}
let seq = fibonacci();
print(seq.next()); // 1
print(seq.next()); // 2
print(seq.next()); // 3
print(seq.next()); // 5
print(seq.next()); // 8
ECMAScript 6 a.k.a Harmony
Coroutinesvar fs = require(‘fs’);
function read(path) {
return function(done){
fs.readFile(path, ‘utf8', done);
}
}
makeCoroutine(function *(){
var a = yield read(‘Readme.md’);
var b = yield read(‘package.json’);
console.log(a);
console.log(b);
});
generator
Koa.jsExpressive middleware for node.js using generators-- by the core team of expres
app.use(function *(next){ var start = new Date; yield next; var ms = new Date - start; this.set('X-Response-Time', ms + 'ms');});
generator
Further Reading● http://latentflip.com/imperative-vs-declarative/● https://medium.com/code-adventures/174f1fe66127● https://github.com/kriskowal/q● http://taoofcode.net/promise-anti-patterns/● http://adit.io/posts/2013-04-17-functors,_applicatives,_and_monads_in_pictures.html
read!
Top Related