Skip to content

Instantly share code, notes, and snippets.

@tokland
Forked from anvk/promises_reduce.js
Last active March 1, 2022 00:18
Show Gist options
  • Star 17 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save tokland/71c483c89903da417d7062af009da571 to your computer and use it in GitHub Desktop.
Save tokland/71c483c89903da417d7062af009da571 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);
@grahaml
Copy link

grahaml commented Nov 15, 2017

Beauty thank you for sharing / posting this!

@jbccollins
Copy link

this is awesome. thank you!

@nicodevs
Copy link

Thanks! What does "ysAcc" stands for?

@cgraff
Copy link

cgraff commented Jun 22, 2018

Exactly what I was looking for. Thanks so much for sharing 👍

@stevegoossens
Copy link

stevegoossens commented Jul 15, 2018

This was really useful. I needed the result to be a Map rather than an Array, so I modified it slightly like this:

function promiseMap(xs, f) {
  const reducer = (ysAcc$, x) =>
    ysAcc$.then(ysAcc => f(x).then(y => { ysAcc[x] = y; return ysAcc; }));
  return xs.reduce(reducer, Promise.resolve({}));
}

works perfectly, I was in a promise chain hell-hole (currently this is the 6th in a 7 stage promise chain), but now it works :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment