Generator 函数的语法

Generator 函数的语法

function* fn1() {
console.log('1111');
yield;
console.log('2222');
yield '你好' //yield
console.log('3333');
return 'hello'
}
let a = fn1()
a.next() //1111
let b = a.next();
console.log(b); //2222 generator.html:27 {value: "你好", done: false}
// a.next() //3333
// a.next()
let c = a.next();
console.log(c);

function* fn2() {
console.log('函数执行。。。。。。');
let a = yield "函数向外传值"
console.log(`我是从外面来的${a}`);
console.log("函数执行完毕");
}
let f1 = fn2()
console.log(f1.next());
f1.next(21212)

function* cook() {
console.log('亲,我只能做,西红柿炒鸡蛋和罗宋汤');
console.log('做菜之前,先检查蔬菜有没有洗好哦');
let info = yield; //用info表示我给你的菜品,需要闯入一个数组,数组里面存储的是蔬菜
//info相当于你执行next()时,需要传入的参数,根据参数在下面函数里做判断
//判断传入的参数,返回相应的状态
//根据状态,返回不同的结果
if (info) {
var state = 0;
if (info[0] === '西红柿' && info[1] === '鸡蛋') {
state = 1;
} else if (info[0] === '西红柿' && info[1] === '牛肉') {
state = 2;
} else {
state = 0;
}
} else {
return '冰箱里没有菜了,做毛线'
}
switch (state) {
case 0:
console.log('啥也没有,做啥做');
setTimeout(() => {
console.log('你还是叫外卖吧');
}, 3000);
break;
case 1:
console.log('准备做西红柿炒鸡蛋');
setTimeout(() => {
console.log('翠花上菜咯(西红柿炒鸡蛋)');
}, 3000);
break;
case 2:
console.log('准备做罗宋汤');
setTimeout(() => {
console.log('翠花上菜咯(罗宋汤)');
}, 3000);
default:
break;
}
}
let a = cook()
a.next()
a.next(['西红柿', '鸡蛋'])

posted @ 2019-08-14 19:54  des雷锋  阅读(...)  评论(...编辑  收藏