Skip to content

Instantly share code, notes, and snippets.

@afc163
Last active August 29, 2015 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save afc163/05c03121d25c5cf38054 to your computer and use it in GitHub Desktop.
Save afc163/05c03121d25c5cf38054 to your computer and use it in GitHub Desktop.
// 当前的 Generator
var activeGenerator;
// 控制工具
function start(generatorFunc) {
activeGenerator = generatorFunc(function(data) {
activeGenerator.next(data);
});
activeGenerator.next();
}
function getData(done) {
// 这个函数模拟一个异步操作,将在 1 秒后触发回调函数
setTimeout(function() {
done('data1');
}, 1000);
}
function getMessage(done) {
// 这个函数模拟一个异步操作,将在 1.5 秒后触发回调函数
setTimeout(function() {
done('message1');
}, 1500);
}
// 声明一个 Generator 并传给 gQueue
start(function * flow(next) {
console.log('start');
// 执行异步函数 asyncFunc,并把 next 注册在其回调函数里
var data = yield getData(next);
// 回调执行完成后,会触发 g.next(),此时 y 的值为 asyncFunc 回调里的 100
console.log('data is', data);
// 同上
var message = yield getMessage(next);
console.log('message is ', message);
console.log('end')
});
// 当前的 Generator
var activeGenerator;
// 控制工具
function start(generatorFunc) {
activeGenerator = generatorFunc();
var next = function() {
var ret = activeGenerator.next();
if (typeof ret.value === 'function') {
ret.value.call();
setImmediate(next);
}
};
return next;
}
function getData() {
return function(done) {
setTimeout(function() {
done('data1');
}, 1000);
}
}
function getMessage() {
return function(done) {
setTimeout(function() {
done('message1');
}, 1500);
}
}
// 声明一个 Generator 并传给 gQueue
start(function * flow() {
console.log('start');
// 执行异步函数 asyncFunc,并把 next 注册在其回调函数里
var data = yield getData();
// 回调执行完成后,会触发 g.next(),此时 y 的值为 asyncFunc 回调里的 100
console.log('data is', data);
// 同上
var message = yield getMessage();
console.log('message is ', message);
console.log('end')
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment