generator和函数不同的是,generator由function*
定义(注意多出的*
号)
除了return
语句,还可以用yield
返回多次
function* test() { let x = 1 yield x + 1; yield x + 2; return x + 3; } const gen = test() console.log(gen) console.log(gen.next()) console.log(gen.next()) console.log(gen.next()) console.log(gen.next())
generator还有另一个巨大的好处,就是把异步回调代码变成“同步”代码
例:
实现async await
function asyncFn() { return new Promise((resolve, reject) => { setTimeout(() => { console.log(111) resolve(222) }, 1000) }) } function asyncFn2() { return new Promise((resolve, reject) => { setTimeout(() => { console.log(333) resolve(444) }, 1000) }) } function* test() { yield asyncFn(); yield asyncFn2(); yield ‘ddd‘; return 3; } const gen = test() function step(gen) { const { value, done } = gen.next() res = value if(done) return // Promise.resolve如果参数是 Promise 实例,那么Promise.resolve将不做任何修改、原封不动地返回这个实例。 Promise.resolve(value).then((res) => { step(gen) console.log(res) }) } step(gen)