Skip to content

Instantly share code, notes, and snippets.

@deepak
Created February 4, 2015 07:35
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/f0d2066bbedd51c3add3 to your computer and use it in GitHub Desktop.
Save deepak/f0d2066bbedd51c3add3 to your computer and use it in GitHub Desktop.
do not throw error directly for generator. always wrap in a callback ?
// works: https://gist.github.com/deepak/ffe01c81900d12f95658
// does not work: https://gist.github.com/deepak/9a7337d7a641f8af9c8b
// difference is that, if error is thrown directly from fucntion called in generator
// then it gives a "Generator is already running" error
// but if it is wrapped in a setTimeout callback then it works
// WORKS
let price = 10;
let stockPrice = function () {
setTimeout(function() {
iterator.next(price++);
}, 300);
}
let errorInStockPrice = function() {
setTimeout(function() {
iterator.throw("oops!");
}, 300);
}
let stockTicker = function*() {
try {
price = yield stockPrice();
console.log("price is " + price); //=> price is 10
price = yield errorInStockPrice();
console.log("price is " + price); //=> price is 10
price = yield stockPrice();
console.log("price is " + price); //=> price is 10
} catch (ex) {
console.log("error in stock-price: " + ex); //=> error in stock-price: Error: oops!
}
};
var iterator = stockTicker();
console.log(iterator.next()); //=> {"done":false}
// DOES NOT WORK
let price = 10;
let stockPrice = function () {
setTimeout(function() {
iterator.next(price++);
}, 300);
}
let badErrorInStockPrice = function() {
iterator.throw("oops!");
}
let stockTicker = function*() {
try {
price = yield stockPrice();
console.log("price is " + price); //=> price is 10
price = yield badErrorInStockPrice();
console.log("price is " + price); //=> price is 10
price = yield stockPrice();
console.log("price is " + price); //=> price is 10
} catch (ex) {
console.log("error in stock-price: " + ex); //=>
//=> error in stock-price: Error: Generator is already running
// expected, error in stock-price: Error: oops!
}
};
var iterator = stockTicker();
console.log(iterator.next()); //=> {"done":false}
@deepak
Copy link
Author

deepak commented Feb 4, 2015

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