Created
February 4, 2015 07:35
-
-
Save deepak/f0d2066bbedd51c3add3 to your computer and use it in GitHub Desktop.
do not throw error directly for generator. always wrap in a callback ?
This file contains hidden or 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
// 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} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
continuation of https://gist.github.com/deepak/ffe01c81900d12f95658
and https://gist.github.com/deepak/9a7337d7a641f8af9c8b