repeaterjs / repeater

The missing constructor for creating safe async iterators
https://repeater.js.org
MIT License
459 stars 12 forks source link

Question about merging two Repeaters #71

Closed qstyler closed 3 years ago

qstyler commented 3 years ago

Hi guys! I was trying out your library and faced the behaviour that I don't understand.

I have two Repeaters that randomly fetch jokes from the APIs. And I want these two Repeaters merged.

When ran apart each Repeater will yield 3 jokes as expected.

For some reason, this code will return me only 4 jokes when I expect 6 of them. Can someone explain to me what am I doing wrong here?

Here's the code:

const axios = require('axios');
const { Repeater } = require('@repeaterjs/repeater');

function getDadJokes(n) {
    return new Repeater(async (push) => {
        for (i = 0; i < n; i++) {
            const { data: { joke } } = await axios.request({
                url: 'https://v2.jokeapi.dev/joke/Any?type=single'
            });
            push(`${joke}`);
        }
    })
}

function getChuckNorrisJokes(n) {
    return new Repeater(async (push) => {
        for (i = 0; i < n; i++) {
            const { data: { value } } = await axios.request({
                url: 'https://api.chucknorris.io/jokes/random'
            });
            push(`${value}`);
        }
    });
}

(async function () {
    const merged = Repeater.merge([
        getChuckNorrisJokes(3),
        getDadJokes(3),
    ]);

    for await (const joke of merged) {
        console.log(`\n${joke}\n`);
    }
})();
brainkim commented 3 years ago

You had me worried for a sec there! I believe the problem is that you need to add a let before each i in the for loop initialization. Because you’re not adding the i, the variable is being shared by both functions in a global scope! If you add let to both loops, you will see 6 jokes logged to the console.

Let me know if this helps!

brainkim commented 3 years ago

Closing as resolved! If you have any more questions, please feel free to ping me or whatever!