koa-async
A Node.js Koa wrapper for caolan/async.
Requirements
- Node.js v4.x+ for ES6 generators support
Usage
First, install the package using npm:
npm install koa-async --save
Then, require the koa-async
package and add the yield
keyword before each async
invocation, omitting the "done" callback function, as demonstrated here:
var async = require('koa-async');
var items = [1, 2, 3];
yield async.each(items, function(item, cb) {
cb();
});
var filter = yield async.filter(items, function(item, cb) {
cb(null, item === 2);
});
this.body = { result: filter };
Koa Example
Here's a more complete example that includes creating a basic Koa app and using various async
methods (also available in examples/async.js
):
var async = require('koa-async');
var app = require('koa')();
app.use(function* () {
var items = [1, 2, 3];
yield async.each(items, function(item, cb) {
cb();
});
console.log('[Test]', 'async.each:', 'done');
var filter = yield async.filter(items, function(item, cb) {
cb(null, item === 2);
});
console.log('[Test]', 'async.filter:', filter);
try {
yield async.each(items, function(item, cb) {
if (item == 3) {
cb('This is a test error message.');
}
});
}
catch (err) {
console.log('[Test]', 'async.error:', err);
}
});
var port = process.env.PORT || 3000;
app.listen(port);
console.log('Server listening on port ' + port);
Run the script and visit http://localhost:3000/ to test it out. Check your Node.js console to see the test output.
License
Apache 2.0