var gen = function* () { try { yieldconsole.log("a") } catch (e) {} yieldconsole.log("b") yieldconsole.log("c") } var g = gen() g.next() // 'a' g.throw() // 'b' g.next() // 'c'
Generator 函数体内抛出的错误也能被函数体外的 catch 捕获:
1 2 3 4 5 6 7 8 9 10 11 12
function* foo() { var x = yield3 var y = x.toUpperCase() yield y } var it = foo() it.next() // { value : 3, done : false } try { it.next(32) } catch (e) { console.log(e) //TypeError }
一旦 Generator 执行过程中抛出错误,就不会再执行下去。如果此后再调用 next,将返回一个 value 属性等于 undefined,done 属性等于 true 的对象。
Generator.prototype.return()
返回给定的值,并终结 Generator 函数的遍历:
1 2 3 4 5 6 7 8 9
function* gen() { yield1 yield2 yield3 } var g = gen() g.next() // { value : 1, done : false } g.return("foo") // { value : 'foo', done : true } g.next() // { value : undefined, done : true }
function* iterTree(tree) { if (Array.isArray(tree)) { for (let i = 0; i < tree.length; i++) { yield* iterTree(tree[i]) } } else { yield tree } } const tree = ["a", ["b", "c"], ["d", "e"]] for (let x ofiterTree(tree)) console.log(x) // a b c d e
function* main() { var result = yieldrequest("http://some.url") var resp = JSON.parse(result) console.log(resp.value) } functionrequest(url) { makeAjaxCall(url, function (response) { it.next(response) }) } var it = main() it.next()
async *[Symbol.asyncIterator]() { for (let i = this.from, to = this.to; i < to; i++) { awaitnewPromise((resolve) =>setTimeout(resolve, 1000)) yield i } }, }
;(asyncfunction () { // for await of will call the [Symbol.asyncIterator] forawait (const value of range) console.log(value) })()