为了更斜体文字好的理解生成器+Promise协同运作模式,自己自定义一个独立工具run(..),它会自动异步运行传递给它的生成器,直到结束
----------
Examples:
// 把基于回调的代码转换为基于Promise的代码:
if(!Promise.wrap) {
Promise.wrap = function(fn) {
return function() {
var args = [].slice.call(arguments);
return new Promise((resolve, reject) => {
fn.apply(null, args.concat(function(err, data) {
if(err) {
reject(err);
}else {
resolve(data);
}
}));
});
};
};
}
function calc(x, y, cb) {
var sum = x + y;
if(sum < 10) {
cb(null, sum);
}else {
cb(new Error("stack overflow"));
}
}
// Generator Runner
function run(gen) {
var args = [].slice.call(arguments, 1);
var it = gen.apply(this, args);
return Promise.resolve().then(function handleNext(val) {
var next = it.next(val);
return (function handleResult(next) {
if(next.done) {
return next.value;
}else {
return Promise.resolve(next.value).then(handleNext, function handleError(err) {
return Promise.resolve(it.throw(err)).then(handleResult);
});
}
})(next);
});
}
function* gen() {
try {
var res1 = yield Promise.wrap(calc)(1, 2);
console.log("res1: ", res1);
var res2 = yield Promise.wrap(calc)(5, 6);
console.log("res2: ", res2);
} catch(e) {
console.error(e);
}
// 测试抛出异常后是否继续执行
var res3 = yield Promise.wrap(calc)(3, 4);
console.log("res3: ", res3);
return "the end";
}
run(gen).then(val => console.log(val), err => console.error(err));
console output:
res1: 3
Error: stack overflow(…)
res3: 7
the end
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。