生成器对象是由一个 generator function 返回的,并且它符合可迭代协议和迭代器协议。
<script>
function *go(){
console.log("a");
return 2;
}
/* done表示generate函数是否执行完毕,value是generate函数的返回值 */
var obj = go();
/*
1.*
2.next()
3. obj.next() value,done
*/
console.log(obj.next())
</script>
generator函数遇到yield关键字 函数会暂停 yield将函数切割了
next( )方法会返回一个对象
<script>
function *gen(x){
yield x+2;
yield 7;
return x;
}
/* generator函数遇到yield关键字 函数会暂停 yield将函数切割了
next()方法会返回一个对象
*/
var g = gen(3);
console.log(g.next())//{value: 5, done: false}
console.log(g.next()) //{value:3,done:true}
console.log(g.next())
</script>
<script>
function *go(x){
var y = yield x+2;
console.log(y)
var z = yield y+10;
console.log(z);
return 4;
}
var obj = go(3);
console.log(obj.next())
console.log(obj.next(7))
console.log(obj.next(8))
</script>
co
co = generator + promise
<script src="https://cdn.bootcss.com/co/4.1.0/index.js"></script>
<script>
async function go(x){
return x;
}
co(function *(){
var data = yield go(3);
console.log(data)
var y = yield go(4);
console.log(y)
})
</script>
generator-http
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script>
<script>
var baseUrl = "http://localhost:3000/"
function http(url){
return $.ajax({
url:baseUrl+url,
dataType:"json"
})
}
function *getData(){
var id = yield http("top/playlist");
console.log(id);
yield http(`playlist/detail?id=${id}`);
}
var res = getData();
res.next().value.then(data=>{
var {id,name} = data.playlists[0];
res.next(id).value.then(res=>{
console.log(res)
})
})
</script>
co-http
<script src="https://cdn.bootcss.com/co/4.1.0/index.js"></script>
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script>
<script>
var baseUrl = "http://localhost:3000/"
function http(url) {
return $.ajax({
url: baseUrl + url,
dataType: "json"
})
}
co(function *(){
const data = yield http("top/playlist");
var {id,name} = data.playlists[0];
const detail = yield http(`playlist/detail?id=${id}`)
console.log(detail)
})
</script>
iterator
<script>
function generator(arr){
var nextIndex = 0;
return {
next:()=>{
if(nextIndex<arr.length){
return {value:arr[nextIndex++],done:false}
}else{
return {done:true}
}
}
}
}
var arr = ["起床",'吃中饭','睡觉'];
var obj = generator(arr);
console.log(obj.next());
console.log(obj.next());
console.log(obj.next());
console.log(obj.next());
</script>