Skip to content

Instantly share code, notes, and snippets.

@nagyadam2092
Created April 10, 2021 07:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nagyadam2092/6bd214f3a17edb389da9975d066a6d12 to your computer and use it in GitHub Desktop.
Save nagyadam2092/6bd214f3a17edb389da9975d066a6d12 to your computer and use it in GitHub Desktop.
Conditional/dynamic array promise all
interface DynamicPromiseResult {
data: unknown;
promise: string;
}
const promises: Array<Promise<DynamicPromiseResult>> = []
if (true) { // some logic
const promise1 = fetch('https://jsonplaceholder.typicode.com/posts/1').then(data => ({ data, promise: 'promise1' }));
promises.push(promise1);
}
if (false) { // some logic
const promise2 = fetch('https://jsonplaceholder.typicode.com/posts/2').then(data => ({ data, promise: 'promise2' }));
promises.push(promise2);
}
const results = await Promise.all(promises)
results.forEach(result => {
// pattern matching would be lovely here, but JS/TS does not support it yet
switch (result.promise) {
case 'promise1':
doSomething();
break;
case 'promise2':
doSomething2();
break;
default:
throw new Error('Resulting promise not found');
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment