Skip to content

Instantly share code, notes, and snippets.

@ricardocanelas
Last active December 22, 2019 11:30
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 ricardocanelas/4b726499b8afce4d63f96dffce84313d to your computer and use it in GitHub Desktop.
Save ricardocanelas/4b726499b8afce4d63f96dffce84313d to your computer and use it in GitHub Desktop.
JavaScript - Promise Map
// https://codesandbox.io/s/promisemap-o7f7n
const getData = id =>
new Promise((res, rej) => {
setTimeout(() => {
const data = { id, uid: (Math.random() * 100).toFixed(2) };
console.log("data", data);
res(data);
}, 100);
});
function promiseMap(inputValues, mapper) {
const reducer = (acc$, inputValue, index) =>
acc$.then(acc =>
mapper(inputValue, index).then(result => acc.push(result) && acc)
);
return inputValues.reduce(reducer, Promise.resolve([]));
}
const ids = [1, 5, 3, 4, 9];
promiseMap(ids, id => {
const start = new Date();
console.log();
console.log("Loading... ", id);
// return a Promise
return getData(id).then(data => {
const end = new Date();
const time = end - start;
console.log(`Loaded in ${time} secs`, data);
// return some data
return data;
});
}).then(values => {
console.log("\n---\n");
console.info("All values:");
values.forEach(item => console.log(item));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment