Last active
December 22, 2019 11:30
-
-
Save ricardocanelas/4b726499b8afce4d63f96dffce84313d to your computer and use it in GitHub Desktop.
JavaScript - Promise Map
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
// 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