今天小編髮現一個es6中的新概念,同時也接觸到了一個新關鍵字yeild,下面我就簡單和大家聊聊es6中的generator函式。大家還可以關注我的微信公眾號,蝸牛全棧。
一、函式宣告:在function和函式名之間存在星號,並使用關鍵字yeild
- function* foo(){
- for(let i = 0;i<3;i++){
- console.log(i) // 什麼也沒輸出
- yield i
- }
- }
- console.log(foo()) // Generator
二、next方法
- function* foo(){
- for(let i = 0;i<3;i++){
- yield i
- }
- }
- let f = foo()
- // f.next() 返回yeild後面的表示式
- console.log(f.next()) // {value:0,done:false}
- console.log(f.next()) // {value:1,done:false}
- console.log(f.next()) // {value:2,done:false}
- console.log(f.next()) // {value:undefind,done:true}
三、yeild只能在generator函式內部使用,不能在外面使用
- function* gen(agrs){
- agrs.forEach(item => {
- yield item += 1
- })
- }
- gen() // 報錯:
四、next函式返回值
- // next 返回yeild後面表示式返回的值
- function* gen(x){
- let y = 2 * (yield(x + 1))
- let z = yield(y/3)
- return x + y + z
- }
- let g = gen(5)
- console.log(g.next()) // {value:6,done:false}
- console.log(g.next()) // {value:NaN,done:false}
- console.log(g.next()) // {value:NaN,done:true}
五、例項敲7遊戲:當前原始碼只是將7的倍數打印出來
- function* count(x=1){
- while(true){
- if(x%7 === 0){
- yield x
- }
- x++
- }
- }
- // 可以一步一步執行,防止了死迴圈的問題
- let n = count()
- console.log(n.next().value) // 7
- console.log(n.next().value) // 14
- console.log(n.next().value) // 21
- console.log(n.next().value) // 28
- console.log(n.next().value) // 35
六、對非同步的管理:(目錄結構:在當前檔案下存在一個static資料夾,資料夾內有三個檔案a.json、b.json、c.json。每個檔案內是一個物件,分別為{a:"我是a"}、{b:"我是b"}、{c:"我是c"})
- function ajax(url, callback) {
- // 1、建立XMLHttpRequest物件
- var xmlhttp
- if (window.XMLHttpRequest) {
- xmlhttp = new XMLHttpRequest()
- } else { // 相容早期瀏覽器
- xmlhttp = new ActiveXObject('Microsoft.XMLHTTP')
- }
- // 2、傳送請求
- xmlhttp.open('GET', url, true)
- xmlhttp.send()
- // 3、服務端響應
- xmlhttp.onreadystatechange = function () {
- if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
- var obj = JSON.parse(xmlhttp.responseText)
- // console.log(obj)
- callback(obj)
- }
- }
- }
- function request(url){
- ajax(url,res=>{
- getData.next(res)
- })
- }
- function* gen(){
- let res1 = yeild request("static/a.json")
- console.log(res1) // {a:"我是a"}
- let res2 = yeild request("static/b.json")
- console.log(res2) // {b:"我是b"}
- let res3 = yeild request("static/c.json")
- console.log(res3) // {c:"我是c"}
- }
- let getData = gen()
- getData.next()