javascript 发电机
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript 发电机相关的知识,希望对你有一定的参考价值。
const co = require('co');
const p1 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Hello');
}, 250);
});
const p2 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('World');
}, 100);
});
// Promise.all([p1, p2]).then((values) => {
// console.log(values);
// });
co(function* () {
const a = yield p1;
const b = yield p2;
console.log(a, b);
});
/*
- Struktura podobna do wzorca Observable
- Przypomina maszynę stanu - pamięta stworzoną kolekcję danych i zwraca kolejne wartości
- Generator jest specyficznym typem funkcji, która może być pauzowan i wznawiana
*/
// Funkcja generatora zwraca obiekt generatora (iterator), który może być iterowany przez właściwość next zwracającą kolejne wartości
function* g() {
yield 1;
yield 2;
yield 3;
}
// console.log(g()); // g {<suspended>}
const iterator = g();
/*
console.log(iterator.next()); // {value: 1, done: false}
console.log(iterator.next()); // {value: 2, done: false}
console.log(iterator.next()); // {value: 3, done: false}
console.log(iterator.next()); // {value: undefined, done: true}
*/
// console.log([...iterator]); // [1,2,3]
/*
for (let value of iterator) {
console.log(value); // 1, 2, 3
}
*/
// ---
function* a() {
const a = yield "2+2?";
console.log('A:', a);
const b = yield "3+3?";
console.log('B:', b);
if(a === 4 && b === 6) return "Cool!";
return "Not cool :(";
}
const iterator2 = a();
// The next time next() is called, execution resumes with the statement immediately after the yield.
console.log('Uno:', iterator2.next());
console.log('Duo:', iterator2.next(4));
console.log(iterator2.next(6));
// ---
{
function* c() {
let i = 0;
while(true) {
yield i++;
}
}
const i = c();
console.log(i.next().value);
console.log(i.next().value);
console.log(i.next().value);
console.log(i.next().value);
}
以上是关于javascript 发电机的主要内容,如果未能解决你的问题,请参考以下文章