-
-
Save valentinvieriu/85fa1a2fe809929cd924eac541764736 to your computer and use it in GitHub Desktop.
Sequential execution of axios get requests using reduce()
This file contains 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 axios = require('axios'); | |
function random(min, max) { | |
return (Math.random() * ((max ? max : min) - (max ? min : 0) + 1) + (max ? min : 0)) | 0; | |
} | |
function wait(promise) { | |
const seconds = random(300, 2000); | |
return new Promise((resolve, reject) => { | |
setTimeout(() => resolve(promise()), seconds); | |
}); | |
} | |
function promiseMap(promisesArray, mapper) { | |
const reducer = (previousPromises, currentPromise) => | |
previousPromises.then(previouseResults => mapper(currentPromise).then(axiosResponse => { console.log(previouseResults, axiosResponse.data)}));// | |
return promisesArray.reduce(reducer, Promise.resolve([])); | |
} | |
const getAxiosPromise = id => () => { | |
return axios.get(`http://localhost:3000/process/${id}`); | |
}; | |
const getAxiosPromise = id => () => { | |
return axios.get(`http://localhost:3000/?page=${id}`); | |
}; | |
[1,2,3,4,5,6,7,8,9,10].forEach((id) => axiosCalls.push(getAxiosPromise(id))); | |
promiseMap(axiosCalls, wait).then(results => { | |
console.log(results); // all calls have been fired | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment