Created
February 4, 2015 08:15
-
-
Save deepak/e325fa2d1a39984fd3e9 to your computer and use it in GitHub Desktop.
calling next in yielded method give a generator already running error
This file contains 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
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} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
http://davidwalsh.name/async-generators
We could change the implementation of request(..) to something like this:
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.