1 - 用法
function * fn() {
yield 1
yield 2
return 3
}
const gen = fn() // 执行fn函数返回一个 Generator对象
// value:当次返回的值 done:表示Generator函数是否执行完毕
console.info(gen.next()) // {value: 1, done: false}
console.info(gen.next()) // {value: 2, done: false}
console.info(gen.next()) // {value: 3, done: true}
判断一个函数是否为Generator函数:
Object.prototype.toString.call(function * (){}); // => "[object GeneratorFunction]"
2 - Generator函数和Async/await的区别
1、Async/await
await 会等待Promise执行完成后返回值,才会执行之后的代码。
async函数会一次执行完毕。
async function afun() {
const data = await new Promise((res, rej) => {
setTimeout(() => {
res(1)
}, 1000)
})
console.info(data)
await console.info(2)
}
afun()
// 先打印1 再打印2
2、Generator函数
yield不会等待Promise执行完成。
Generator函数执行时会返回一个Generator对象,之后需要通过next() 操作来获取 yield 返回的值
function * fun() {
yield new Promise((res, rej) => {
setTimeout(() => {
res(1)
}, 1000)
})
yield console.info(2)
}
const a = fun()
// 第一次执行 next() 时,返回的promise对象处于 padding 状态,需要 .then 来等待 promise 执行完毕
a.next().value.then(data => console.info(data))
a.next()
// 先打印2 再打印1