I’m working on a project where I need to make several API calls in sequence. My main concern is avoiding rate limit issues while keeping the code efficient. I’ve tried using a simple loop but I’m worried about overwhelming the API server.
Here’s my current approach that needs improvement:
if (requestData.type === "photo") {
for (let index = 0; index < requestData.items.length; index++) {
try {
const config = {
method: "POST",
headers: {
accept: "application/json",
"content-type": "application/json",
authorization: "Bearer my-token-here",
},
body: JSON.stringify({
file: `${requestData.items[index].file}`,
}),
};
const result = await fetch(
`https://api.example.com/upload/photo?description=${encodeURIComponent(
requestData.items[index].description
)}&recipient=${userId}`,
config
);
const responseData = await result.json();
console.log(`Photo ${index + 1} uploaded:`, responseData);
await waitTime();
} catch (err) {
console.error(`Failed to upload photo ${index + 1}:`, err);
}
}
return { status: "Upload completed" };
}
What’s the most effective way to handle multiple API requests while preventing rate limit violations? I need all requests to complete successfully regardless of individual response status.