Last active
November 8, 2024 08:57
-
-
Save Soumyarian98/c1ffa1b560d6f97eed2bb6cdf1f9a4ea 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
| const tasks: Array<() => Promise<number>> = [ | |
| () => new Promise((res) => res(10)), | |
| () => new Promise((_, rej) => rej(new Error('Failed to fetch data'))), | |
| () => new Promise((res) => res(30)), | |
| ]; | |
| const executor = new SequentialPromiseExecutor(tasks); | |
| executor.startProcessing().then((results) => { | |
| results.forEach((result, index) => { | |
| if (result.success) { | |
| console.log(`Task ${index} succeeded with value:`, result.value); | |
| } else { | |
| console.error(`Task ${index} failed with error:`, result.error); | |
| } | |
| }); | |
| }); |
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
| class SequentialPromiseExecutor<T> { | |
| constructor(private tasks: Array<() => Promise<T>>) {} | |
| // Async generator to yield results one by one | |
| async *processQueue(): AsyncGenerator<Result<T>, void, unknown> { | |
| for (const task of this.tasks) { | |
| try { | |
| const result = await task(); | |
| yield { success: true, value: result }; | |
| } catch (e) { | |
| yield { success: false, error: e as Error }; // Yield the original error | |
| } | |
| } | |
| } | |
| // Method to start processing and return an array of results | |
| async startProcessing(): Promise<Result<T>[]> { | |
| const results: Result<T>[] = []; | |
| for await (const result of this.processQueue()) { | |
| results.push(result); | |
| } | |
| return results; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment