[英]Why doesn't the generator return the following value?
For each call to the "loop" function, I try to return a new value of the "c" property from the "test" object, but for some reason, I get the same value of every function call.对于对“循环”函数的每次调用,我尝试从“测试”对象返回“c”属性的新值,但出于某种原因,每次函数调用都会得到相同的值。
1 call: {value: {a: 1}, done: false}
2 call: {value: {a: 1}, executed: false}
3 call: {value: {a: 1}, done: false}
instead of getting a new value for every call而不是每次调用都获得一个新值
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')); }
In fact, this is a simulation of the logic that I want to implement.其实这是对我要实现的逻辑的模拟。 In reality, I imitate the response of the server when the names of the requests come, I want to give a certain set of data, but some requests will come several times and ask for the same data structure but with different values, so the function "loop" will be called independently.
在现实中,我是模仿请求名称来时服务器的响应,我想给出一组特定的数据,但是有些请求会多次来请求相同的数据结构但具有不同的值,所以函数“循环”将被独立调用。
You have to create a generator only once, and then call next()
as you need您只需创建一次生成器,然后根据需要调用
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());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.