I'm trying to fetch data using the Spotify API endpoint, this is my code:
  //gets around 300+ items from my MongoDB
  let artistsArray = []
  const artists = await Artist.find({ createdBy: userId })
  const sleep = m => new Promise(r => setTimeout(r, m))
  const fetchData = async (artist, groupType) => {
    try {
      const data = await axios.get(
        `/artists/${artist.artistSpotifyId}/albums?include_groups=${groupType}&limit=5`,
      )
      
      // working with data here, putting it into the artistArray not important
      
    } catch (error) {
      if (error.response.status === 429) {
        //rate limit error, if received, sleep for suggested time and retry
        const retryAfter = parseInt(error.response.headers['retry-after']) * 1000
        await sleep(retryAfter)
        await fetchData(artist, groupType)
      }
    }
  }
  //should go through each artist and get albums for each artist
  await Promise.all(
    artists.map(async artist => {
      await fetchData(artist, 'album')
      await fetchData(artist, 'single')
    }),
  )
When I tested that with few items, it worked fine, however with higher amount of items(mentioned 300+) I started getting rate limit errors 429 from Spotify. They always suggest retry-after period so I tried to implement it in the catch, so there'd be a sleep triggered every time error is catched but I can't seem to figure out why it doesn't work using the .map. When error 429 gets encountered, the loop just continues.
When using for loop, it works just fine, but it's kind of slow and therefore I haven't encountered any rate limit error.
for (let artist of artists) {
    await fetchData(artist, 'album')
    await fetchData(artist, 'single')
  }
Any suggestion why is .map ignoring the sleep function?
 
     
     
    