-
-
Save deepak/e325fa2d1a39984fd3e9 to your computer and use it in GitHub Desktop.
let price = 10; | |
let stockPrice = function () { | |
setTimeout(function() { | |
iterator.next(price++); | |
}, 300); | |
} | |
let badStockPrice = function () { | |
iterator.next(price++); | |
} | |
let stockTicker = function*() { | |
// var v1 = stockPrice(); | |
var vi = badStockPrice(); | |
price = yield v1; | |
console.log("price is " + price); | |
}; | |
var iterator = stockTicker(); | |
console.log(iterator.next()); //=> {"done":false} |
http://davidwalsh.name/async-generators
We could change the implementation of request(..) to something like this:
var cache = {};
function request(url) {
if (cache[url]) {
// "defer" cached response long enough for current
// execution thread to complete
setTimeout( function(){
it.next( cache[url] );
}, 0 );
}
else {
makeAjaxCall( url, function(resp){
cache[url] = resp;
it.next( resp );
} );
}
}
Note: A subtle, tricky detail here is the need for the setTimeout(..0) deferral in the case where the cache has the result already. If we had just called it.next(..) right away, it would have created an error, because (and this is the tricky part) the generator is not technically in a paused state yet. Our function call request(..) is being fully evaluated first, and then the yield pauses. So, we can't call it.next(..) again yet immediately inside request(..), because at that exact moment the generator is still running (yield hasn't been processed). But we can call it.next(..) "later", immediately after the current thread of execution is complete, which our setTimeout(..0) "hack" accomplishes.
continuation of https://gist.github.com/deepak/f0d2066bbedd51c3add3