Skip to content

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 }
// ]

注意事項

  1. 並行執行: 所有 Promise 同時開始執行
  2. 錯誤處理: 任何一個 Promise 失敗都會導致整個操作失敗
  3. 順序: 結果數組的順序與輸入 Promise 數組的順序一致
  4. 性能: 比順序執行快,但會消耗更多資源

與其他函數的區別

  • all: 並行執行所有 Promise
  • Promise.all: 原生方法,功能相同
  • race: 返回第一個完成的 Promise
  • any: 返回第一個成功的 Promise

性能

  • 時間復雜度: O(n),其中 n 是 Promise 數量
  • 並發: 所有 Promise 並行執行
  • 適用場景: 需要同時執行多個獨立操作

Released under the MIT License.