1

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

    });

});
1
  • 1
    That pushes into the array just fine (assuming 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 the found_songs array appropriately. If you try to use it right after the .forEach() loop, it will still be empty. Use a regular for loop which is await aware, not .forEach(). Commented Apr 21, 2020 at 20:16

1 Answer 1

4

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))
Sign up to request clarification or add additional context in comments.

1 Comment

Promise.all is much better in author's case, cause he is dealing with API / client//server side, it will high improve speed and short delay of his endpoint. But I also recommend using Promise.allSettled instead (developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…) because if one (getSong) will fail, it rejects the whole array of methods.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.