Skip to content

Instantly share code, notes, and snippets.

@nikolasburk
Last active October 17, 2022 07:53
Show Gist options
  • Save nikolasburk/ada98b3506e8a919252ec2d5f6d350f4 to your computer and use it in GitHub Desktop.
Save nikolasburk/ada98b3506e8a919252ec2d5f6d350f4 to your computer and use it in GitHub Desktop.
import "isomorphic-fetch";
console.log("Start ...");
const numberOfRequests = 100;
async function main() {
// 1. Create x requests (as unresolved promises)
console.log(`Creating ${numberOfRequests} requests ...`);
const requests = [];
for (let i = 0; i < numberOfRequests; i++) {
const request = fetch(
`https://plain-nextjs-data-proxy-test-1.vercel.app/api/user?name=custom-test-${numberOfRequests}`
);
requests.push(request);
}
// 2. Run all requests at once
console.log(`Run all requests at once ...`);
const resultsArray = await Promise.all(requests);
// 3. Collect results
const result = {
twoHundreds : 0,
fiveHundreds : 0
}
resultsArray.forEach((response, i) => {
console.log(`Request finished: ${response.status}`, response.statusText);
if (response.status === 200) {
result.twoHundreds++;
} else if (response.status === 500) {
result.fiveHundreds++;
} else {
console.log(`${i}: ${response.status}`, response.statusText);
}
});
// 4. Display result
console.log(`Result: `, result)
}
main();
/**
*
const initialValue = { fiveHunreds: 0, twoHundreds: 0 };
const finalResult = resultsArray.reduce((prev, result) => {
if (result.status === 200) {
prev.twoHundreds++;
} else if (result.status === 500) {
prev.fiveHunreds++;
}
}, initialValue);
const array1: any[] = [];
const sumWithInitial = array1.reduce(
(previousValue, currentValue) => previousValue + currentValue,
initialValue
);
*/
/**
*
async function main() {
// 1. Create 100 requests (as unresolved promises)
console.log(`Creating ${numberOfRequests} requests ...`);
const requests = [];
for (let i = 0; i < numberOfRequests; i++) {
const request = fetch(
`https://plain-nextjs-data-proxy-test-1.vercel.app/api/user?name=custom-test-${numberOfRequests}`
);
requests.push(request);
}
// 2. Run all requests at once
// console.log(`Run all requests at once ...`);
// const resultsArray = await Promise.all(requests);
// 3. Collect results
const result = {
twoHundreds: 0,
fiveHundreds: 0,
};
requests.forEach(async (request: any, i: number) => {
const response = await request;
console.log(`[${Date.now}] Request finished: ${response.status}`, response.statusText);
if (response.status === 200) {
result.twoHundreds++;
} else if (response.status === 500) {
result.fiveHundreds++;
} else {
console.log(`${i}: ${response.status}`, response.statusText);
}
});
// 4. Display result
console.log(`Result: `, result);
}
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment