博客園 @四季留歌。 前置技術條件:
es6 Promise
;es7 async、await
有時候不想在 async 函數中寫太多 await 語句,例如:
const doSth = async () => {
const response1 = await fetch('/api1')
const json1 = await response1.json()
const response2 = await fetch('/api2')
const buffer = await response2.arrayBuffer()
// ...
}
可以使用 Promise.all
來實現同時請求:
// 如果都是要轉成 json
const urls = ['/api1', '/api2']
const doSth = async () => {
const results = await Promise.all(urls.map(
url => fetch(url).then(response => response.json()) // 注意這個箭頭函數,是 map 所執行的
))
console.log(results) // 倆 json
}
如果每個接口請求返回的數據格式要求不太一樣的話,那就要稍微麻煩一點
const requests = [
{ url: '/api1', format: 'json' },
{ url: '/api2', format: 'arrayBuffer' }
]
const doSth = async () => {
const results = await Promise.all(requests.map(
request => {
const { url, format } = request
return fetch(url).then(response => response[format]()) // 注意此處使用計算屬性來獲取轉換函數
}
))
console.log(results) // 一個 json,一個 arrayBuffer
}