The second countermeasure of Callback Hell is using co.
co is a library which utilizes Generator mechanism and make it easy to write serial and parallel flows.
const co = require('co');
const thunkify = require('thunkify')
var callbackFunction = function(message, timeout, callback) {
setTimeout(function() {
console.log(message);
callback(null, message);
}, timeout);
};
var thunkifiedFunction = thunkify(callbackFunction);
var promiseFunction = function(message, timeout) {
return new Promise(function(resolve, reject){
setTimeout(function() {
console.log(message);
resolve(message);
}, timeout);
});
};
co(function*() {
console.log('--- co start ---');
var response = yield [
thunkifiedFunction('co two', 800),
promiseFunction('co one', 600),
];
console.log("response: " + JSON.stringify(response));
yield thunkifiedFunction('co three', 200);
yield promiseFunction('co four', 400);
yield wrappedFunction();
console.log('--- co end ---');
return "Generator finished.";
}).then(function(value){
console.log('--- then start ---');
console.log(value);
}).catch((error) => {
console.log('--- error start ---');
console.log(error);
});
var wrappedFunction = co.wrap(function* () {
console.log('--- co.wrap start ---');
var response = yield [
thunkifiedFunction('co.wrap two', 800),
thunkifiedFunction('co.wrap one', 600),
];
console.log("co.wrap response: " + JSON.stringify(response));
yield thunkifiedFunction('co.wrap three', 200);
yield thunkifiedFunction('co.wrap four', 400);
console.log('--- co.wrap end ---');
return yield Promise.resolve(null);
});
Result
$ node co_generator.js
--- co start ---
co one
co two
response: ["co two","co one"]
co three
co four
--- co.wrap start ---
co.wrap one
co.wrap two
co.wrap response: ["co.wrap two","co.wrap one"]
co.wrap three
co.wrap four
--- co.wrap end ---
--- co end ---
--- then start ---
Generator finished.