Learn Generators – 4 » CATCH ERROR!
该解决方案使用for循环,但是我在 MDN – Iteration Protocols中找不到任何指向回调期间的收益的内容.
该解决方案使用for循环,但是我在 MDN – Iteration Protocols中找不到任何指向回调期间的收益的内容.
我要猜测答案是不要这样做,但如果有人有时间或倾向提供解释,提前感谢!
码:
- function *upper (items) {
- items.map(function (item) {
- try {
- yield item.toUpperCase()
- } catch (e) {
- yield 'null'
- }
- }
- }
- var badItems = ['a','B',1,'c']
- for (var item of upper(badItems)) {
- console.log(item)
- }
- // want to log: A,B,null,C
错误:
- ⇒ learn-generators run catch-error-map.js
- /Users/gyaresu/programming/projects/nodeschool/learn-generators/catch-error-map.js:4
- yield item.toUpperCase() // error below
- ^^^^
- SyntaxError: Unexpected identifier
- at exports.runInThisContext (vm.js:73:16)
- at Module._compile (module.js:443:25)
- at Object.Module._extensions..js (module.js:478:10)
- at Module.load (module.js:355:32)
- at Function.Module._load (module.js:310:12)
- at Function.Module.runMain (module.js:501:10)
- at startup (node.js:129:16)
- at node.js:814:3
即使我的编辑知道这是一个可怕的想法…
解决方法
免责声明:我是
Learn generators研讨会的作者.
@slebetman的回答是正确的,我也可以添加更多:
是的,MDN – Iteration Protocol没有直接指出回调期间的收益率.
但是,它告诉我们,从产生项目的重要性,因为您只能使用生成器内的收益.请参阅MDN – Iterables文档以了解更多信息.
@marocchino suggest只是精细的解决方案迭代在map之后被改变的数组:
- function *upper (items) {
- yield* items.map(function (item) {
- try {
- return item.toUpperCase();
- } catch (e) {
- return null;
- }
- });
- }
我们可以这样做,因为Array有迭代机制,见Array.prototype[@@iterator]().
- var bad_items = ['a','c'];
- for (let item of bad_items) {
- console.log(item); // a B 1 c
- }
Array.prototype.map没有默认的迭代行为,所以我们无法迭代.
但是发电机不仅仅是迭代器.每个生成器都是迭代器,反之亦然.生成器允许您通过调用yield关键字来自定义迭代(而不仅仅是)进程.您可以在这里播放并查看生成器/迭代器之间的区别:
演示:babel/repl.