0

I've a get route in Nodejs. I'm accessing data from the database and looping through that data. I've a fetch twitch API request inside that loop which is using an attribute from that data. I've to filter the data in a way that if it the response is null then it should ignore it and if there is any data, it should append that into an array. Then at the end, it should return that array which have filtered data. But the problem is that it is returning empty array even though the data is coming from the API. I think this is the variable scope issue but I don't know how should I resolve it. Following is my code:

router.get("/getstreams", async (req, res) => {
var arr = [];
await UserStreams.find().then(async (allStreams) => {
    console.log(allStreams[0].user_id);
    const a = allStreams.map(async (data) => {
        return await fetch(`https://api.twitch.tv/kraken/streams/${data.user_id}`, {
            headers: {
                Accept: "application/vnd.twitchtv.v5+json",
                "Client-ID": "yfzf3ux4gltxrcnentffrfvmlg7cwx",
                Authorization: "Bearer xbbxf3cbtuwz4i5gkekxjb338p28yr",
            },
            method: "GET",
        })
            .then(async (res) => {
                return await res.json();
            })
            .then(async (json) => {
                return await (json !== null && arr.push(json));
            });
    });
    console.log("array = ", arr);
    console.log("array2 = ", a);
    res.send(a);
});

});

Ali Ahmad
  • 51
  • 1
  • 1
  • 4
  • You'll want to use `Promise.all`. That will allow you to wait for all the streams before sending a response. – Bergi Sep 26 '20 at 20:32
  • Hi, Thank you for your reply. This is not Promise issue. This is variable scope issue. Can you give that code snippet which you're saying because I don't understand that. – Ali Ahmad Sep 26 '20 at 21:37
  • No, it's not a scope issue, `arr` is perfectly in scope everywhere it is used. It's an asynchrony issue - you send the response and only later fill the array. – Bergi Sep 26 '20 at 21:40
  • I've updated the question, Now, I'm using async functions with await but still no luck. – Ali Ahmad Sep 26 '20 at 22:24
  • Now just throw in an `await Promise.all(a)` and you're set :-) – Bergi Sep 26 '20 at 23:12
  • I did it. It is not pushing JSON data to the array. Rather, it is return some numbers like this: array2 = [ 1, 2, 5, 4, 3, 8, 6, 9, 7, 10, 11, 12 ] – Ali Ahmad Sep 26 '20 at 23:23
  • It is resolved. I used spread operator instead of push method. It worked. You really saved my day man. Thank you so much! – Ali Ahmad Sep 26 '20 at 23:28

0 Answers0