Created
April 4, 2018 22:04
-
-
Save ericblade/9139d021be023679da3c1a480a47cc54 to your computer and use it in GitHub Desktop.
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
/* An incredibly handy function to run several (probably related) Promises simultaneously, | |
* allowing for any given Promise to reject, results will be returned in an object with same key names as the input | |
*/ | |
/* example: | |
* const x = { | |
* api1: () => callApi1(), | |
* api2: () => callApi2(), | |
* api3: () => callApi3(), | |
* }; | |
* const r = await multiApiCall(x); | |
* // r = { api1: api1results, api2: api2results, api3: api3results } | |
*/ | |
/* for a more interesting exercise, say you have 3 items that you want to call 3 different remote APIs on | |
* so you want to make 9 simultaneous API calls to get the data as fast as you can, and await all of them to complete. | |
* you can do this by creating an array of 'x' objects like above, let's call it 'arr', then do: | |
* const apiCalls = arr.map(api => multiApiCall(api)); | |
* const res = await Promise.all(apiCalls); | |
*/ | |
function multiApiCall(obj) { | |
const funcs = Object.entries(obj); | |
const promises = funcs.map(([name, func]) => ( | |
func && func.call() | |
.then(ret => (console.warn('* ', name, 'returns'), [name, ret])) | |
.catch(err => { | |
console.warn('**** Error in ', func, ':', err); | |
return [name, err]; | |
}) || [name, undefined] | |
) | |
); | |
return Promise.all(promises).then(arr => ( | |
arr.reduce((accumulator, [name, ret]) => (accumulator[name] = ret, accumulator), {}) | |
)); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment