Skip to content

Instantly share code, notes, and snippets.

@aflansburg
Created May 18, 2018 14:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aflansburg/82f6aecac3563c60e0e0496e467ea47d to your computer and use it in GitHub Desktop.
Save aflansburg/82f6aecac3563c60e0e0496e467ea47d to your computer and use it in GitHub Desktop.
Cascading Async/Await Delay against an Array - Node.js
// slight modification and re-application of daliborgogic/delay.js
const timeout = ms => new Promise(res => setTimeout(res, ms));
// index is the index of an array member
async function throttle(index){
console.log(`Index ${index} will fire after ${1500*index}ms`);
return timeout(index*1500);
}
// let's say you have an async operation that makes requests to certain endpoints
// that you've wrapped in a new Promise
let requestResponses =
urls.map(url=>{
return new Promise((resolve, reject) =>{
// now for each array member you are cascading the timeout
throttle(urls.indexOf(url))
.then(()=>{
// do something async here such as making a request using request-promise-native, axios, etc.
// since you are cascading your timeout using the index there is exactly 1.5ms between each call
request.get(url)
.then(data=>{
resolve(data);
});
});
});
});
Promises.all(requestResponses)
.then(responses=>console.log(responses));
@aflansburg
Copy link
Author

Slight modification and re-application of daliborgogic/delay.js

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment