Skip to content

Instantly share code, notes, and snippets.

@deepak
Created February 4, 2015 08:15
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 deepak/e325fa2d1a39984fd3e9 to your computer and use it in GitHub Desktop.
Save deepak/e325fa2d1a39984fd3e9 to your computer and use it in GitHub Desktop.
calling next in yielded method give a generator already running error
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}
@deepak
Copy link
Author

deepak commented Feb 4, 2015

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment