简体   繁体   中英

How to use recursions with yield?

Is there a way to mix the yield generator with recursions in Vanilla Javascript?

I have a use case really close the the code below, please don't mind the async/await as there are promises in the original.

The issue is that the following example iterates only once.

let n = 0;

async function* atGet(offset=undefined) {
    if (n == 0) offset = true;

    if (n < 5) yield n;
  
    if (!!offset) {
        n = n + 1;
        atGet(n);
    }
}

const init = async () => {
    try {
        for await (let n of atGet()) {
            console.log(n)
        }
    }
    catch(err) {
        throw err;
    }
};

init();

I'm wondering what I am doing incorrectly, any advice is welcome.

You need to yield* the call of the generator function as well.

if (offset) yield* atGet(n + 1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM