co is the classic generator-based async control flow library that paved the way for modern async/await syntax in JavaScript and Node.js.
Executing Generators
const co = require('co');
co(function* () {
const result = yield Promise.resolve(42);
return result * 2;
}).then(val => {
console.log(val); // 84
}).catch(err => {
console.error(err);
});
A generator function can yield Promises, thunks, arrays, or objects of promises. co() executes the generator to completion immediately.
Generator to Reusable Promise Function (co.wrap)
Converts a generator into a standard function returning a regular Promise (identical to modern async function):
const getUser = co.wrap(function* (id) {
const user = yield db.users.findById(id);
const posts = yield db.posts.findByUser(user.id);
return { user, posts };
});
// Calling returns a Promise:
getUser(123).then(data => {
console.log(data);
});
Working with Node.js Callback APIs
Using thunkify or modernized promisified wrappers (like mz or native fs.promises):
const thunkify = require('thunkify');
const fs = require('fs');
const readFile = thunkify(fs.readFile);
co(function* () {
const content = yield readFile('config.json', 'utf8');
console.log(JSON.parse(content));
});
Parallel Execution (Arrays & Objects)
co(function* () {
// Parallel resolution in array
const [user, profile] = yield [fetchUser(), fetchProfile()];
// Parallel resolution in object
const data = yield {
user: fetchUser(),
profile: fetchProfile()
};
console.log(data.user, data.profile);
});