co co è la classica libreria di controllo di flusso asincrono basata su generatori che ha aperto la strada alla sintassi async/await in JavaScript.
Esecuzione di generatori
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);
});
Una funzione generatore può eseguire lo yield di promise, thunk, array o oggetti. co() esegue il generatore fino al completamento.
Da generatore a funzione promise riutilizzabile (co.wrap)
Converte un generatore in una funzione standard che restituisce una promise (identica alle moderne funzioni async):
const getUser = co.wrap(function* (id) {
const user = yield db.users.findById(id);
const posts = yield db.posts.findByUser(user.id);
return { user, posts };
});
// La chiamata restituisce una normale promise:
getUser(123).then(data => {
console.log(data);
});
Integrazione con le API a callback di Node.js
Utilizzo di thunkify o wrapper con promise:
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));
});
Esecuzione parallela (Array e Oggetti)
co(function* () {
// Risoluzione parallela in un array
const [user, profile] = yield [fetchUser(), fetchProfile()];
// Risoluzione parallela in un oggetto
const data = yield {
user: fetchUser(),
profile: fetchProfile()
};
console.log(data.user, data.profile);
});