all
并行执行多个异步操作,返回所有结果。
语法
typescript
all<T>(
promises: Promise<T>[]
): Promise<T[]>
参数
promises
(Promise<T>[]): 要并行执行的 Promise 数组
返回值
Promise<T[]>
: 包含所有结果的 Promise
示例
基本用法
typescript
import { all } from 'radash'
const promises = [
Promise.resolve(1),
Promise.resolve(2),
Promise.resolve(3)
]
const results = await all(promises)
// [1, 2, 3]
异步函数数组
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' }
// ]
处理错误
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)
// 任何 Promise 失败都会导致整个操作失败
}
文件操作
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']
数据库查询
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)
混合操作
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)
条件执行
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)
// 只包含用户数据
超时处理
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秒超时
]
try {
const [data] = await all(promises)
console.log('Data received:', data)
} catch (error) {
console.error('Request failed or timed out:', error)
}
进度跟踪
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 }
// ]
注意事项
- 并行执行: 所有 Promise 同时开始执行
- 错误处理: 任何一个 Promise 失败都会导致整个操作失败
- 顺序: 结果数组的顺序与输入 Promise 数组的顺序一致
- 性能: 比顺序执行快,但会消耗更多资源
与其他函数的区别
all
: 并行执行所有 PromisePromise.all
: 原生方法,功能相同race
: 返回第一个完成的 Promiseany
: 返回第一个成功的 Promise
性能
- 时间复杂度: O(n),其中 n 是 Promise 数量
- 并发: 所有 Promise 并行执行
- 适用场景: 需要同时执行多个独立操作