co co ist die klassische generatorbasierte asynchrone Kontrollflussbibliothek, die den Weg für die moderne async/await-Syntax in JavaScript und Node.js ebnete.
Generatoren ausführen
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);
});
Eine Generatorfunktion kann Promises, Thunks, Arrays oder Objekte mit Promises mittels yield abwarten. co() führt den Generator sofort bis zum Abschluss aus.
Generator in wiederverwendbare Promise-Funktion umwandeln (co.wrap)
Wandelt einen Generator in eine Standardfunktion um, die ein reguläres Promise zurückgibt (identisch mit modernen async functions):
const getUser = co.wrap(function* (id) {
const user = yield db.users.findById(id);
const posts = yield db.posts.findByUser(user.id);
return { user, posts };
});
// Gibt bei Aufruf ein reguläres Promise zurück:
getUser(123).then(data => {
console.log(data);
});
Zusammenarbeit mit Node.js-Callback-APIs
Verwendung von thunkify oder modernen Promisified-Wrappern:
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));
});
Parallele Ausführung (Arrays & Objekte)
co(function* () {
// Parallele Auflösung im Array
const [user, profile] = yield [fetchUser(), fetchProfile()];
// Parallele Auflösung im Objekt
const data = yield {
user: fetchUser(),
profile: fetchProfile()
};
console.log(data.user, data.profile);
});