Skip to content

Instantly share code, notes, and snippets.

@atomize
Forked from tokland/promise_map.js
Created August 17, 2018 21:30
Show Gist options
  • Save atomize/264e41d3448cd56748b13f7b0e44919b to your computer and use it in GitHub Desktop.
Save atomize/264e41d3448cd56748b13f7b0e44919b to your computer and use it in GitHub Desktop.
Execute an array of promises sequentially and collect the result
function promiseMap(xs, f) {
const reducer = (ysAcc$, x) =>
ysAcc$.then(ysAcc => f(x).then(y => ysAcc.push(y) && ysAcc));
return xs.reduce(reducer, Promise.resolve([]));
}
/* Example */
const axios = require('axios');
function countryFromIp(ip) {
return axios.get("http://freegeoip.net/json/" + ip).then(res => res.data.country_name);
}
promiseMap(["8.8.8.8", "41.182.194.0", "5.34.159.1"], countryFromIp).then(console.log);
// [ 'United States', 'Namibia', 'Spain' ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment