Last active
February 18, 2023 01:53
-
-
Save twosdai/bdd25e366480478855d890f696257d04 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//const fetch = require("node-fetch"); | |
const apiEndpoint = "http://api.open-notify.org/iss-now.json"; | |
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); | |
/** | |
* | |
* Below are a few examples of how to use async stuff inside of JS. I am using the ISS now API for the async request. | |
*/ | |
// To force some ASYNC method to run synchronously, I reccomend using a for loop or a do while loop to force the code to run in order. | |
// This is useful for pagination or when you really need to be sure that a previous request executed before the next one. I reccomend only doing this if you have less than 20 Http calls to make. total | |
// As a rule of thumb I associate about 300ms with an HTTP call, which is a little conservative, but helps me to plan for the worst case scenario. | |
const forceSync = async () => { | |
for (let i = 0; i < 10; i++) { | |
const response = await fetch(apiEndpoint); | |
const data = await response.json(); | |
console.log(data); | |
} | |
}; | |
// forceSync(); | |
/** | |
* Now lets run all of these requests in parallel. This is useful when you have a lot of requests to make, but you don't care about the order of the responses. | |
* I've provided two different examples which are exactly the same, but one uses a for loop and the other uses a map function. I prefer the map function, but it's up to you. | |
* | |
* Importantly Promise.all() will resolve or reject each promise as they come up in whatever order they finish, if a promise rejects it stops the execution of the other promises and doesn't complete them. | |
* This is important to know. | |
* | |
* If you want to run all of the promises and then resolve/reject them all at the end, you can use Promise.allSettled() instead. (See runParallel2) | |
* */ | |
const runParallel1 = async () => { | |
const promises = []; | |
for (let i = 0; i < 10; i++) { | |
promises.push(fetch(apiEndpoint)); | |
console.log(i); | |
if (i === 2) { | |
throw new Error("Something went wrong!"); | |
} | |
} | |
const responses = await Promise.all(promises); | |
// Will not execute since Promise.all() will reject if any of the promises reject. | |
const data = await Promise.all(responses.map((r) => r.json())); | |
console.log(data.length); | |
}; | |
// runParallel1(); | |
const runParallel2 = async () => { | |
const promises = []; | |
for (let i = 0; i < 10; i++) { | |
if (i == 2) { | |
promises.push(Promise.reject(new Error("Something went wrong!"))); | |
} else { | |
promises.push(fetch(apiEndpoint)); | |
} | |
} | |
const responses = await Promise.allSettled(promises); | |
const sucessfulPromises = responses.filter((r) => r.status === "fulfilled"); | |
console.log(sucessfulPromises.length); // Should be 9 since one promise failed. | |
}; | |
// runParallel2(); | |
const runParallel3 = async () => { | |
const results = await Promise.all( | |
[...Array(10).keys()].map(async (element, index) => { | |
const response = await fetch(apiEndpoint); | |
const data = await response.json(); | |
// Notice that the index may not be listed in order, since they are concurrently resolved. | |
console.log(index); | |
if (index === 2) { | |
// Just to show that the other promises may still finish even if one fails. However it is NOT guaranteed that they will finish. | |
await sleep(100); | |
throw new Error("Something went wrong!"); | |
} | |
return data; | |
}) | |
); | |
// The below line will not execute since await Promise.all() will reject if any of the promises reject. | |
console.log(results.length); | |
}; | |
// runParallel3(); | |
const runParallel4 = async () => { | |
const results = await Promise.allSettled( | |
[...Array(10).keys()].map(async (element, index) => { | |
const response = await fetch(apiEndpoint); | |
const data = await response.json(); | |
console.log(index); | |
if (index === 2) { | |
throw new Error("Something went wrong!"); | |
} | |
return data; | |
}) | |
); | |
const sucessful = results.filter((r) => r.status === "fulfilled"); | |
console.log(sucessful.length); // Should be 9 since one promise failed. | |
}; | |
// runParallel4(); | |
const runParallel5 = async () => { | |
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); | |
const promises = [...Array(10).keys()]; | |
extraArray = []; | |
for (const id of promises) { | |
await sleep(1000); | |
console.log(id); | |
extraArray.push(id); | |
} | |
console.log(extraArray); | |
}; | |
//runParallel5(); | |
const runParallel6 = async () => { | |
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); | |
const promises = [...Array(10).keys()]; | |
const idArray = await Promise.all( | |
promises.map(async (id) => { | |
await sleep(1000); | |
// Doesn't Block, also can be out of order, however .map() will return them in order. | |
console.log(id); | |
return id; | |
}) | |
); | |
console.log(idArray); | |
}; | |
// runParallel6(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment