Last active
August 29, 2015 14:02
-
-
Save afc163/05c03121d25c5cf38054 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 当前的 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') | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 当前的 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