This document discusses callbacks, promises, and generators for handling asynchronous code in JavaScript. It begins by explaining callbacks and the issues they can cause like "callback hell". It then introduces promises as an alternative using libraries like Q that allow chaining asynchronous operations together. Generators are also covered as a way to write asynchronous code that looks synchronous when combined with promises through libraries like CO. Overall, it recommends using an asynchronous pattern supported by a library to manage complex asynchronous code.
21. callbacks, promises, generators
Promises
According to Promises/A+ specification
„promise is an object or function with a then method
whose behavior conforms to this specification (...)
[and] represents the eventual result of an
asynchronous operation„
More specs http://wiki.commonjs.org/wiki/Promises
29. callbacks, promises, generators
Promises - previous waterfall example
var fetchFromDb = function() {
return Q.ninvoke(db, 'fetch')
.then(Q.denodeify(serializeResults));
};
!
fetchFromDb()
.then(function(result) {
result;
});
You have to convert each callback-based function into promise-based
for chaining
30. callbacks, promises, generators
Promises - MAP
var promisedSum = Q.denodeify(sum);
!
var promises = [1, 2, 3, 4, 5].map(function(num) {
return promisedSum(num);
});
!
Q.all(promises).then(function(result) {
console.log(result);
});
Q.all is a custom Q library function.
Not in spec.
31. callbacks, promises, generators
Promises - compatibility
https://github.com/kriskowal/q#the-middle
„When working with promises provided by other libraries,
you should convert it to a Q promise. Not all
promise libraries make the same guarantees as Q and
certainly don’t provide all of the same methods.”
39. callbacks, promises, generators
Generators - introducing CO
CO
by TJ Holowaychuk
„The ultimate generator based flow-control goodness
for nodejs (supports thunks, promises, etc)”
40. callbacks, promises, generators
Generators - CO
var fetchResultFromDb = function*() {
var records = yield thunkify(db.fetch.bind(db))();
return yield thunkify(serializeResults)(records);
};
!
co(function*() {
var result = yield fetchResultFromDb;
})();
41. callbacks, promises, generators
Generators - THUNK
var asyncFunction = function(arg1, arg2, calback) {
setTimeout(function() {
callback(null, {tasty: 'sandwich with '+arg1+' and '+arg2})
}, 50);
};
co(function*() {
yield asyncFunction; // what about arguments?
yield asyncFunction.bind(undefined, 'butter', 'cheese');
})();
47. callbacks, promises, generators
More informations
Promises/A+ Performance Hits You Should Be Aware Of
https://github.com/substack/node-seq
http://wiki.commonjs.org/wiki/Promises