Skip to content

Instantly share code, notes, and snippets.

@farminf
Created February 17, 2022 13:38
Show Gist options
  • Save farminf/82808eb003c38582abfb15d23f0be3a3 to your computer and use it in GitHub Desktop.
Save farminf/82808eb003c38582abfb15d23f0be3a3 to your computer and use it in GitHub Desktop.
HTTP calls in series with delay between
/**
I wanted to call an endpoint updating an entity and I wanted to do it for 500 entities.
The API server had "rate limit" and I couldn't just use Promise.all
I wrote this script just to call each update and have a 2 second delay between
them to make sure API server would not block them
*/
import fetch from "node-fetch";
import { sessions } from "./data.js";
const bearerToken = ""
const updateSession = (sessionId) => {
console.log(`updating session ${sessionId}`);
return fetch(
`https://www.url/${sessionId}`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${bearerToken}`,
},
}
);
};
const delay = () => {
console.log(`Waiting: 2 seconds.`);
return new Promise((resolve) => {
setTimeout(() => {
resolve("2");
}, 2000);
});
};
const startTime = Date.now();
const doNextPromise = async (sessionID) => {
delay()
.then((x) => {
console.log(
`Waited: ${x} seconds now calling the endpoint for updating session ${sessions[sessionID]}`
);
return updateSession(sessions[sessionID])
.then((res) => {
if (res.status !== 200) {
throw `Error updating session ${sessions[sessionID]}: ${res.status}`;
}
return res.json();
})
.then((res) =>
console.log(`Response: ${JSON.stringify(res)} for session ${sessions[sessionID]}`)
)
.catch((e) => console.log(`Error: ${e}`));
})
.then((res) => {
sessionID++;
if (sessionID < sessions.length) doNextPromise(sessionID);
else console.log(`Total: ${(Date.now() - startTime) / 1000} seconds.`);
});
};
doNextPromise(0);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment