Skip to content

Instantly share code, notes, and snippets.

@AceroM
Created August 14, 2025 23:40
Show Gist options
  • Select an option

  • Save AceroM/220a965d31db0e2c5ff2fc397eed7ada to your computer and use it in GitHub Desktop.

Select an option

Save AceroM/220a965d31db0e2c5ff2fc397eed7ada to your computer and use it in GitHub Desktop.
async operations in promise all
import { performance } from "perf_hooks"
// Simulates an async operation (e.g., API call, database query)
async function simulateAsyncOperation(
id: number,
delay: number
): Promise<number> {
await new Promise((resolve) => setTimeout(resolve, delay))
return id * 2
}
// Sequential approach - waits for each promise to complete before starting the next
export async function runSequential(): Promise<void> {
const startTime = performance.now()
const results: number[] = []
console.log("Starting sequential execution...")
for (let i = 1; i <= 5; i++) {
const result = await simulateAsyncOperation(i, 1000)
results.push(result)
console.log(`Sequential: Completed operation ${i}, result: ${result}`)
}
const endTime = performance.now()
const totalTime = endTime - startTime
console.log(`Sequential results: ${results}`)
console.log(`Sequential execution time: ${totalTime.toFixed(2)}ms`)
}
// Parallel approach using Promise.all - all promises run concurrently
export async function runPromiseAll(): Promise<void> {
const startTime = performance.now()
console.log("Starting Promise.all execution...")
const promises = Array.from({ length: 5 }, (_, i) => {
const id = i + 1
return simulateAsyncOperation(id, 1000).then((result) => {
console.log(`Promise.all: Completed operation ${id}, result: ${result}`)
return result
})
})
const results = await Promise.all(promises)
const endTime = performance.now()
const totalTime = endTime - startTime
console.log(`Promise.all results: ${results}`)
console.log(`Promise.all execution time: ${totalTime.toFixed(2)}ms`)
}
// Run both approaches and compare
async function compareApproaches(): Promise<void> {
console.log("=== Performance Comparison: Sequential vs Promise.all ===\n")
await runSequential()
console.log("\n---\n")
await runPromiseAll()
console.log("\n=== Summary ===")
console.log("Sequential: ~5000ms (5 operations � 1000ms each)")
console.log("Promise.all: ~1000ms (all operations run in parallel)")
}
if (import.meta.main) {
await compareApproaches()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment