I am trying to push some objects into 'found_songs' array from an asynchronous function. Is there any proper way to do it? Thanks!
app.post('/api/spotify/get-songs', async function (req, res) {
let selected_songs = req.body;
let found_songs = [];
selected_songs.forEach(async function (song) {
let temp = await getSong(song);
found_songs.push(temp);
});
});
getSong()returns a promise that resolves to the song). But,.forEach()is not promise-aware so it doesn't wait for your promises so you will not have any idea when all the songs are in the array and will not be able to use thefound_songsarray appropriately. If you try to use it right after the.forEach()loop, it will still be empty. Use a regularforloop which isawaitaware, not.forEach().