0.0.14 • Published 10 years ago
simplerun v0.0.14
simple-run
Simple flow control utility based on generators
Installation
npm install simplerun
Usage
done
callback is used for functions that only return value like fs.exists.
function(val) {}
type callback: the return value of yield statement will be the actual result.- If there are more than one arguments in callback like
function(val1, val2, val3)
, the yield statement will return array of values like val1, val2, val3.
var simplerun = require('simplerun');
var fs = require('fs');
// function (data) {} type callback
simplerun(function* (done){
var exists = yield fs.exists('./index.js', done);
console.log('./index.js exist? ' + exists);
})();
errorDone
callback is used for functions that have callback where first argument is error like most functions in MongoDB.
- If error was passed in to callback, the yield statement will throw an exception.
- If no error was passed, yield statement will return arguments except the first one (error).
var simplerun = require('../index.js');
var request = require('request');
simplerun(function* (errorDone){
try {
var a = yield request.get('http://google.com', errorDone);
console.log(a[0].statusCode);
var b = yield request.get('http://baidu.com', errorDone);
console.log(b[0].statusCode);
var c = yield request.get('http://a-web-site-that-does-not-exist.com', errorDone);
console.log(c[0].statusCode);
} catch (e) {
console.log(e);
}
})();
Simplerun provide a finish
callback to return final value of the running block.
It can be used together with thunkify style flow utility like co
or used to retrieve return value.
Work with co
var co = require('co');
var simplerun = require('../index.js');
co(function* () {
var a = yield simplerun(function* (finish) {
finish(1);
});
console.log(a);
})
Use finish
to retrieve return value.
var simplerun = require('../index.js');
function finishCallback(val) {
console.log(val);
}
simplerun(function* (done) {
yield fs.exists('./index.js', done);
return 2;
})(finishCallback);
Tests
npm test