为数组Generator JS中的每个项目生成收益

问题描述 投票:0回答:1

我正在尝试使生成器更灵活

来自此:

function *formValidationSequence () {
    yield someRef.current.func()
    yield someOtherRef.current.func()
    ...
} 

到此:

const array = [someRef, someOtherRef]

const handler = (array) => {
    const sequence = testSequence(function *() {
        yield* array.map(item => item.current.func())
    })
}

但是它不起作用。我想为数组中的每个引用/项目动态创建yield,而无需立即调用它们。

应该怎么做?

javascript generator
1个回答
0
投票

[map将对数组中的每个项目执行该函数,然后再对其调用yield*。如果您希望每次迭代仅调用一个函数,则只需使用常规循环即可:

function*() {
    for (const el of array) {
        yield el.current.func();
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.