run-async-gen v1.2.0
run-async-gen
Utility function for running asynchronous JavaScript generators
Install
npm install run-async-gen --saveAPI
runAsyncGen(iter, cb)
iteriterator created byasyncGencb(err, result)callback is called whenasynGenthrow an exceptionerror return a valueresult
###asyncGen conventions
Asynchronous generator should yield asynchronous function with one callback parameter asyncFunc(cb), this convention follows most of Node.js API. If your asyncFunc requires more than one parameter, you can bind this parameters using lodash utility functions, such as bind, partial and partialRight. The provided callback cb(err, result) should be called with one of two arguments err or result. If err is not null or undefined yield statement will throw exception with this value, it can be handled using standatrd try-catch statements. If no error, yield statement will return result.
To run a number of asynchronous functions in parallel, you can pass to yield statement an array of asynchronous functions [asyncFn1, asyncFun2], then yield will return their results as an array in same order ['result1', 'result2'].
Example
'use strict';
const _ = require('lodash');
const fs = require('fs');
const runAsyncGen = require('run-async-gen');
function* testAsyncGen(delay, times) {
console.log('begin');
for (let i = 0; i < times; i++) {
console.log('Wait', i);
console.log('Stats', yield _.bind(fs.readFile, fs, '/proc/uptime'));
yield _.partialRight(setTimeout, delay);
}
console.log('end');
if (Math.random() > 0.5) {
throw new Error('Error :(');
}
return 'test result';
}
runAsyncGen(testAsyncGen(1000, 4), function(err, result) {
if (err) {
console.error('Error', err);
return;
}
console.log('Result', result);
});
runAsyncGen(testAsyncGen(2000, 2), function(err, result) {
if (err) {
console.error('Error', err);
return;
}
console.log('Result', result);
});