营山网站建设,北京官方网站网,本地wordpress卸载,棋牌app开发软件MDN-Generator Generator对象由生成器函数返回#xff0c;并且它符合可迭代协议和迭代器协议。
Generator-核心语法
核心语法:
定义生成器函数获取generator对象yield表达式的使用通过for of获取每一个yield的值
// 1. 通过function* 创建生成器函数
function* foo() {//… MDN-Generator Generator对象由生成器函数返回并且它符合可迭代协议和迭代器协议。
Generator-核心语法
核心语法:
定义生成器函数获取generator对象yield表达式的使用通过for of获取每一个yield的值
// 1. 通过function* 创建生成器函数
function* foo() {// 遇到yield表达式时会暂停后续的操作yield ayield byield creturn d
}
// 2. 调用函数获取生成器
const f foo()
// 3. 通过next方法获取yield 之后的表达式结果会被包装到一个对象中
// 执行一次next 即可获取一次 yield之后的表达式结果
const res1 f.next()
console.log(res1)// {value: a, done: false}
const res2 f.next()
console.log(res2)// {value: b, done: false}
const res3 f.next()
console.log(res3)// {value: c, done: false}
// 最后一次可以拿到return的结果
const res4 f.next()
console.log(res4)// {value: d, done: true}
// done 为true之后获取到的value为undefined
const res5 f.next()
console.log(res5)// {value: undefined, done: true} // 4. 通过for of 获取每一个yield之后的值
const f2 foo()
for (const iterator of f2) {console.log(iterator)
}总结
Generator-核心语法
可以通过生成器函数(function* xxx(){})来生成Generator对象通过Generator对象的next方法可以获取yield表达式之后的结果
Generator-id生成器
使用Generator实现一个id生成器id。
核心步骤:
定义生成器函数内部使用循环,通过yield返回id并累加
// 1. 通过function* 创建生成器函数
function* generator() {let id 0// 无限循环while (true) {// id累加并返回yield id}
}
// 2. 调用函数获取生成器
const idMaker generator()
// 3. 需要id的时候 通过next获取即可
const { value: id1 } idMaker.next()
console.log(id1)
const { value: id2 } idMaker.next()
console.log(id2)总结
Generator-id生成器
生成器函数内部的代码会在调用next方法时执行,利用这一特点,可以实现任意的生成器,需要时调用next即可获取结果
Generator-流程控制
遇到yield表达式时会暂停后续的操作。使用Generator实现流程控制。
核心步骤:
yield后面跟上天气查询逻辑接口文档-天气预报参考code:北京 110100 上海 310100 广州 440100 深圳 440300 button classgetWeather天气查询/buttonscript srchttps://cdn.bootcdn.net/ajax/libs/axios/1.3.6/axios.js/scriptscript/*** 需求流程控制依次查询北上广深的天气预报* 参考code: 北京 110100 上海 310100 广州 440100 深圳 440300* 接口文档: https://apifox.com/apidoc/project-1937884/api-49760220* */function* weatherGenerator() {// 北京yield axios(http://hmajax.itheima.net/api/weather?city110100)// 上海yield axios(http://hmajax.itheima.net/api/weather?city310100)// 广州yield axios(http://hmajax.itheima.net/api/weather?city440100)// 深圳yield axios(http://hmajax.itheima.net/api/weather?city440300)}const cityWeather weatherGenerator()document.querySelector(.getWeather).addEventListener(click, async () {const res await genCity.next()console.log(res)})/script同理可以使用 Promise 链式调用。
city.next().value.then(res {console.log(res:, res)return city.next().value
}).then(res {console.log(res:, res)
})总结
Generator-流程控制
使用Generator控制流程的本质是利用yield关键字来分隔逻辑。比如示例中依次调用了多个接口,通过yield分隔,通过next来触发调用。