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);
});
});