对于每次调用“loop”函数,我尝试从“test”对象返回“c”属性的新值,但由于某种原因,我在每个函数调用中得到相同的值。
1 call: {value: {a: 1}, done: false}
2 call: {value: {a: 1}, executed: false}
3 call: {value: {a: 1}, done: false}
而不是为每次调用获取新值
1 call: {value: {a: 1}, done: false}
2 call: {value: {a: 2}, executed: false}
3 call: {value: {a: 3}, done: true}
const test = {
a: { id: 1 },
b: { id: 2 },
c: [{ a: 1 }, { a: 2 }, { c: 3 }]
};
function* generLoop(elem) {
// eslint-disable-next-line no-undef,no-restricted-syntax
for (el of test[elem]) {
// eslint-disable-next-line no-undef
yield el;
}
}
const createLoop = elem => {
const gen = generLoop(elem);
return () => gen.next();
};
function loop(elem) {
const findQuery = Object.keys(test).find(el => el === elem);
if (findQuery) {
const loopIterator = createLoop('c');
loopIterator();
}
return test[elem];
}
for (let i = 0; i < 3; i++) {
console.log(loop('c'));
}
事实上,这就是我想要实现的逻辑的模拟。实际上,我模仿服务器在请求名称到来时的响应,我想给出一组特定的数据,但有些请求会多次到来并要求相同的数据结构但具有不同的值,所以该函数“loop”将被独立调用。
最佳答案
您只需创建一个生成器一次,然后根据需要调用 next()
cosnt createLoop = elem => {
const findQuery = Object.keys(test).find(el => el === elem);
let gen
if (findQuery) {
gen = generLoop('c');
}
return () => gen ? gen.next() : test[elem];
}
const iterator = createLoop('c')
for (let i = 0; i < 3; i++) {
console.log(iterator());
}
关于javascript - 为什么生成器不返回以下值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59903423/