all
Execute multiple async operations in parallel and return all results.
Syntax
typescript
all<T>(
promises: Promise<T>[]
): Promise<T[]>
Parameters
promises
(Promise<T>[]): Array of Promises to execute in parallel
Return Value
Promise<T[]>
: Promise containing all results
Examples
Basic Usage
typescript
import { all } from 'radash'
const promises = [
Promise.resolve(1),
Promise.resolve(2),
Promise.resolve(3)
]
const results = await all(promises)
// [1, 2, 3]
Array of Async Functions
typescript
import { all } from 'radash'
const fetchUser = (id: number) =>
fetch(`/api/users/${id}`).then(res => res.json())
const userIds = [1, 2, 3, 4, 5]
const userPromises = userIds.map(id => fetchUser(id))
const users = await all(userPromises)
// [
// { id: 1, name: 'Alice' },
// { id: 2, name: 'Bob' },
// { id: 3, name: 'Charlie' },
// { id: 4, name: 'Diana' },
// { id: 5, name: 'Eve' }
// ]
Error Handling
typescript
import { all } from 'radash'
const promises = [
Promise.resolve(1),
Promise.reject(new Error('Failed')),
Promise.resolve(3)
]
try {
const results = await all(promises)
} catch (error) {
console.error('One of the promises failed:', error)
// Any Promise failure will cause the entire operation to fail
}
File Operations
typescript
import { all } from 'radash'
import { readFile } from 'fs/promises'
const files = ['file1.txt', 'file2.txt', 'file3.txt']
const readPromises = files.map(file => readFile(file, 'utf8'))
const contents = await all(readPromises)
// ['content1', 'content2', 'content3']
Database Queries
typescript
import { all } from 'radash'
const getUser = (id: number) =>
db.query('SELECT * FROM users WHERE id = ?', [id])
const getPost = (id: number) =>
db.query('SELECT * FROM posts WHERE id = ?', [id])
const userIds = [1, 2, 3]
const postIds = [10, 20, 30]
const [users, posts] = await all([
all(userIds.map(id => getUser(id))),
all(postIds.map(id => getPost(id)))
])
console.log('Users:', users)
console.log('Posts:', posts)
Mixed Operations
typescript
import { all } from 'radash'
const operations = [
fetch('/api/users'),
fetch('/api/posts'),
new Promise(resolve => setTimeout(() => resolve('delayed'), 1000))
]
const [users, posts, delayed] = await all(operations)
Conditional Execution
typescript
import { all } from 'radash'
const shouldFetchUsers = true
const shouldFetchPosts = false
const promises = []
if (shouldFetchUsers) {
promises.push(fetch('/api/users').then(res => res.json()))
}
if (shouldFetchPosts) {
promises.push(fetch('/api/posts').then(res => res.json()))
}
const results = await all(promises)
// Only contains user data
Timeout Handling
typescript
import { all } from 'radash'
const timeout = (ms: number) =>
new Promise((_, reject) =>
setTimeout(() => reject(new Error('Timeout')), ms)
)
const promises = [
fetch('/api/slow-endpoint'),
timeout(5000) // 5 second timeout
]
try {
const [data] = await all(promises)
console.log('Data received:', data)
} catch (error) {
console.error('Request failed or timed out:', error)
}
Progress Tracking
typescript
import { all } from 'radash'
const tasks = [
{ id: 1, promise: fetch('/api/task1') },
{ id: 2, promise: fetch('/api/task2') },
{ id: 3, promise: fetch('/api/task3') }
]
const promises = tasks.map(task =>
task.promise.then(result => ({ id: task.id, result }))
)
const results = await all(promises)
// [
// { id: 1, result: Response },
// { id: 2, result: Response },
// { id: 3, result: Response }
// ]
Notes
- Parallel execution: All Promises start executing simultaneously
- Error handling: Any Promise failure will cause the entire operation to fail
- Order: The order of results array matches the order of input Promise array
- Performance: Faster than sequential execution, but consumes more resources
Differences from Other Functions
all
: Execute all Promises in parallelPromise.all
: Native method, same functionalityrace
: Returns the first completed Promiseany
: Returns the first successful Promise
Performance
- Time Complexity: O(n), where n is the number of Promises
- Concurrency: All Promises execute in parallel
- Use Cases: When multiple independent operations need to be executed simultaneously