Skip to content

Instantly share code, notes, and snippets.

@laphilosophia
Forked from tokland/promise_map.js
Created May 4, 2021 12:29
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 laphilosophia/210349398004fe55a68daf8568fa5a44 to your computer and use it in GitHub Desktop.
Save laphilosophia/210349398004fe55a68daf8568fa5a44 to your computer and use it in GitHub Desktop.
Execute promises sequentially (one at at a time) and return array with the results
function promiseMap(inputValues, mapper) {
const reducer = (acc$, inputValue) =>
acc$.then(acc => mapper(inputValue).then(result => acc.push(result) && acc));
return inputValues.reduce(reducer, Promise.resolve([]));
}
/* Example */
const axios = require('axios');
function countryFromIp(ip) {
return axios.get(`http://ip-api.com/json/${ip}`)
.then(res => res.data.country);
}
promiseMap(["8.8.8.8", "41.182.194.0", "5.34.159.1"], countryFromIp).then(console.log);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment