Created
April 10, 2021 07:02
-
-
Save nagyadam2092/6bd214f3a17edb389da9975d066a6d12 to your computer and use it in GitHub Desktop.
Conditional/dynamic array promise all
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
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