Skip to content

Instantly share code, notes, and snippets.

@evilj0e
Created August 31, 2021 12:43
Show Gist options
  • Save evilj0e/9687f115cf67fa2a37474bf99b20792c to your computer and use it in GitHub Desktop.
Save evilj0e/9687f115cf67fa2a37474bf99b20792c to your computer and use it in GitHub Desktop.
const fn1 = async () => {
console.log('fn1: started');
const promise = new Promise((resolve, reject) => {
setTimeout(() => resolve({ fn1: 'data' }), 1000)
});
console.log(await promise);
return promise;
};
const fn2 = async () => {
console.log('fn2: started');
const promise = new Promise((resolve, reject) => {
setTimeout(() => resolve({ fn2: 'data' }), 100)
});
console.log(await promise);
return promise;
};
const fn3 = async () => {
console.log('fn3: started');
const promise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve({ fn3: 'data' })
}, 500)
});
return promise;
};
const parallel = (...fns) => async (payload) => {
const data = await Promise.allSettled(
fns.map((fn) => fn(payload))
);
return data.reduce(
(acc, resultItem) => ({ ...acc, ...resultItem.value }),
{}
);
}
console.log(await parallel(fn3, fn2, fn1)('payload'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment