Skip to content

Instantly share code, notes, and snippets.

@valentinvieriu
Forked from tokland/promise_map.js
Last active August 22, 2017 12:34
Show Gist options
  • Save valentinvieriu/85fa1a2fe809929cd924eac541764736 to your computer and use it in GitHub Desktop.
Save valentinvieriu/85fa1a2fe809929cd924eac541764736 to your computer and use it in GitHub Desktop.
Sequential execution of axios get requests using reduce()
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