Created
May 18, 2018 14:21
-
-
Save aflansburg/82f6aecac3563c60e0e0496e467ea47d to your computer and use it in GitHub Desktop.
Cascading Async/Await Delay against an Array - Node.js
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
// 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)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Slight modification and re-application of daliborgogic/delay.js