Using setInterval() with a .map method in array and returning as a promise

  api, arrays, javascript, promise, timer

I have a function that takes a list of IDs, converts them into an array URLS, then uses the map function to fire a fetch request. It works great but it fires too fast and the provider throws errors because we hit the API too often. I need to set an interval for the request but everytime I do, it doesn’t really work. Ideas?

async function getReports(reportIDs) {
    const urls = reportIDs.map(id => `https://api.data.com/api/v1/report/${id}/?include_datasets=true`);
    const requests = urls.map(url => fetch(url, {
        method: 'GET',
        headers: { 'api-key': key }
    }).then(res => res.json()));
    
    const responses = await Promise.all(requests).catch(err => console.error(err));
    return responses;
}

I use a promise so I can await the results of the function inside another function to transform the datasets.

Ideas?

Source: Ask Javascript Questions

LEAVE A COMMENT