Skip to content

Instantly share code, notes, and snippets.

@Soumyarian98
Last active November 8, 2024 08:57
Show Gist options
  • Select an option

  • Save Soumyarian98/c1ffa1b560d6f97eed2bb6cdf1f9a4ea to your computer and use it in GitHub Desktop.

Select an option

Save Soumyarian98/c1ffa1b560d6f97eed2bb6cdf1f9a4ea to your computer and use it in GitHub Desktop.
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);
}
});
});
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