-
-
Save atomize/264e41d3448cd56748b13f7b0e44919b to your computer and use it in GitHub Desktop.
Execute an array of promises sequentially and collect the result
This file contains hidden or 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
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