omn_1
omn_1

Reputation: 345

node.js - Pushing to an array from async function

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

    });

});

Upvotes: 1

Views: 2845

Answers (1)

shawn
shawn

Reputation: 196

The parent function is already asynchronous, so you could use a for loop:

app.post('/api/spotify/get-songs', async function (req, res) {
  let selected_songs = req.body;
  let found_songs = [];
  for (let song of selected_songs) {
    let temp = await getSong(song)
    found_songs.push(temp)
  }
});

You could also use Promise.all() to improve performance. That way it's not waiting on each iteration.

const selected_songs = req.body;
const found_songs = await Promise.all(selected_songs.map(song => getSong(song))

Upvotes: 4

Related Questions