1

I have a route on an Express API, that requests an artists details, this response contains an array of releases for that artist.

Currently I'd like to map over that array, extract a url and then make an API call to that url. The response I get back, I'm thinking I need to push into an array, so that array can ultimately be returned as my response. (This is a backend for the front end)

However when I console log my array, it is empty.

I'm using the request-promise library on npm.

Is this correct? I'm thinking I need to somehow ensure all promises are resolved before moving on in my execution, however am unsure how?

route.get('/search', (req, res) => {
    const artist = req.query.artist || '';
    let releases = [];

    rp.get(`https://api.discogs.com/database/search?artist=${artist}&type=release&format=Vinyl&per_page=5&page=1`)
        .then(({results}) => results.map(({resource_url}) => resource_url))
        .then((resource_urls) => resource_urls.map((resource_url) => rp.get(resource_url).then((release) => releases.push(release))))
        .then(() => console.log(releases))
        .catch((err) => console.log(err))
});
Harry Blue
  • 4,202
  • 10
  • 39
  • 78

1 Answers1

0

You can use Promise.all in the chain and not use the releases variable declared before:

route.get('/search', (req, res) => {
    const artist = req.query.artist || '';

    rp.get(`https://api.discogs.com/database/search?artist=${artist}&type=release&format=Vinyl&per_page=5&page=1`)
        .then(({results}) => results.map(({resource_url}) => resource_url))
        .then((resource_urls) => Promise.all(resource_urls.map((resource_url) => rp.get(resource_url)))
        .then((releases) => console.log(releases))
        .catch((err) => console.log(err))
});
Alberto Trindade Tavares
  • 10,056
  • 5
  • 38
  • 46