Last active
July 25, 2017 11:02
-
-
Save belaczek/ba885a22c85494615ffc05ecfe63fd52 to your computer and use it in GitHub Desktop.
Two async map solutions with basic currying support
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
/** | |
* Async map function with currying support | |
* @param fn | |
* @param arr | |
* @return {function(*=)} | |
*/ | |
export const asyncMap = (fn, arr) => { | |
const asyncMapHelper = async arr => { | |
const promiseArray = Array.prototype.map.call(arr, async x => fn(x)); | |
return await Promise.all(promiseArray); | |
}; | |
return arr ? asyncMapHelper(arr) : asyncMapHelper; | |
}; | |
/** | |
* A little bit more elegant way to get the same result as above | |
*/ | |
export const asyncMap2 = async function asyncMap2(fn, arr) { | |
if (arr) { | |
const promiseArray = Array.prototype.map.call(arr, async x => fn(x)); | |
return await Promise.all(promiseArray); | |
} else { | |
return asyncMap2.bind(null, fn); | |
} | |
}; | |
export default asyncMap; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment