Dwell Generator

Generator exactly what kind of role do ????

  • He is a program to solve the asynchronous problem raised by ES6

    Look at the piece of code, feel the difference between the generator function and a normal function

   function* test(){
        yield 2;
        yield 3;
        yield 5;
    }
    var app = test()            // 此时代码不会执行
    var a = app.next()          // 这个时候代码才开始真正开始执行 
    console.log(a)              // {value:2,done:false}
    var b = app.next()          // 继续执行
    console.log(b)              // {value:3,done:false}
    var b = app.next()          // 最后一步
    console.log(b)              // {value:5,done:true}

Can be seen from the above code, generator allows the function to stop running at the time of writing, like when we break point, then I was thinking, if I write asynchronous function is not it also allows him to stop it, excited I quickly tried it

function* getTime(){
    //这里我就用axios打个比方,就不写一段promise了,大家理解这里可以放一个promise就行
    yield axios.get('xxxxx')
}
var app = getTime()
app.next()     //  {value,done}  这里面的value就是返回的axios数据
  • To summarize, then the generator is a solution for asynchronous
  • Now that you know his usefulness, then we have to learn how to use his

Use Promise

  • What is the Promise of writing specifications
// 在写函数的时候必须用一个*  
function* add(){}
function *add(){}
// 那么在es6之后函数可以写成
get(){
    ...
}
//所以还有另外一种写法
*get(){
    
}
  • How to use Promise

    This time need to understand a keyword yield keyword must be within the generator function, like the async must await inside the same

var app = test()  //test是一个generator函数
app.next()        //会把程序中的yield后面的值拿出来,并且吧yield后面的数据传递给返回的对象的value中
//例如
function *test(){
    yield 2
}
test().next()     //test()本身不会执行,当调用next的时候才会执行,就是返回一个对象 {value:2,done:true}
//再理解一下,yield后面的值赋给了value,done是指generator函数后面还存在return或者yield等程序,就是后面时候还有代码段
  • Then we will write a function generator, and will be called
  • If you can pass parameters, then we would not use this function together it is perfect
function* test(){
    console.log('程序开始了')
    console.log(`1.${yield}`)  //这里面我们使用es6的字符串插值方式
    console.log(`2.${yield}`)  //这里面我们调用
}
var app = test()                //这个时候只是让app变成一个指向generator函数的指针,并不会打印出值来
app.next()                     
app.next('第一步')             
app.next('第二步')             
//接下来就是打印的结果了
程序开始执行了
1.第一步
2.第二步
  • Share is not easy, thanks to star

Guess you like

Origin www.cnblogs.com/sunhang32/p/11820301.html