Generator & yield write in sync waypromise
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); })