I am facing an issue with my map function, as it needs to fetch data from an online API that only allows one request per second. I attempted to solve this problem by implementing the following code:
const sleep = (ms: number) => {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
};
const promises = projectData.map(async (project, index) => {
return await getAddress(asdf)
.then((nominatimData) => {
// ....perform some actions...
})
.catch(async (e) => {
console.log("failed", e);
return await sleep(2000).then(() => {
console.log("retrying... ")
return getAddress(asdf);
});
});
});
await Promise.allSettled(promises);
console.log("Project Data", projectData); //fires before all getAddress() are retrieved.. :(
I am encountering two challenges that I cannot resolve:
It seems like the map() function is executing in parallel (is this accurate?), which is not ideal for me because I need it to run sequentially, with a one-second delay between requests.
My sleep function does not appear to be functioning correctly. The console log output is disorganized and simultaneous.
What would be the best approach to ensure that this code executes once every second? Is there a better way to handle retrying "getAddress" if it fails?
Thank you for your assistance!