co + Generator 写的迭代器 类似 async.whilst
试着用用Koa,项目里原来有用到async 的whilst
用koa再用async感觉不太舒服,就用Generator+co写了个类似async whist的调用的主体功能,像传参这些没有作到
var co = require('co'); function* whilstGenerator(next, callback, end) { while (next) { yield callback() } } function whilst(test, callback, end) { var next = test() if (next) { co(whilstGenerator(next, function () { callback(); whilst(test, callback) })) } end() }; if (!module.parent) { var num = 0; whilst(function () { return num++ < 10 }, function () { console.log(num) }, function () { console.log("end") }) } module.exports.whilst = whilst;