Generator & yield write in sync way
var p = new Promise(function(resolve, reject){
setTimeout(function(){
console.log(2);
resolve(2);
},1000);
});
var p2 = new Promise(function(resolve, reject){
setTimeout(function(){
console.log(3);
resolve(3);
},1500);
});
function runGenerator(g) {
var it = g(), ret;
(function iterate(val){
// console.log(val);
ret = it.next( val ); //generator对象next()的值 就是 yield 语句后面表达式的值
if (!ret.done) {
// 检查是否已经then完成
if ("then" in ret.value) { //当yield后的表达式是 promise对象的时候
// 这一句很关键
ret.value.then( iterate );
//记得promise的then如何调用的吗 p.then(function(data){...}) 这样resolve的值就传到iterator中了
}
else {
// 同步回调的trick
setTimeout( function(){
iterate( ret.value );
}, 0 );
}
}
})();
}
runGenerator(function* (){
var result = yield p;
console.log(1, result);
var result = yield p2;
console.log(result);
})