我現在正在向 Promise.all 傳遞 3 個 API 呼叫。現在,對于每個 API 呼叫,我需要創建單獨的錯誤處理程式,并且如果資料正在回傳存盤到它自己的物件(對應于相同的 API 物件名稱)。
如果我傳遞test4給 Promise.all 我怎樣才能讓它生成它自己的錯誤并將資料存盤到狀態物件,而不是我手動添加這些值?
我試過回圈回應,但Object { test3: Promise { "fulfilled" } }沒有資料。
代碼:
import { useCallback, useEffect } from 'react'
const getTest1 = Promise.resolve({ isData: true, isError: false })
const getTest2 = Promise.resolve({ isData: false, isError: true })
const getTest3 = Promise.resolve({ isData: true, isError: false })
export const PromiseAll = () => {
const getInitialData = useCallback(async () => {
try {
const res = await Promise.all([{ test1: getTest1 }, { test2: getTest2 }, { test3: getTest3 }])
for (let i = 0; i < res.length; i ) {
const el = res[i]
console.log('?? ~ el', el)
}
const test1 = await res[0].test1
const test2 = await res[1].test2
const test3 = await res[2].test3
test1.isError && console.log('Error in test1', test1.isError)
test2.isError && console.log('Error in test2', test2.isError)
test3.isError && console.log('Error in test3', test3.isError)
const state = {
test1: test1.isData,
test2: test2.isData,
test3: test3.isData,
}
console.log('?? ~ state', state)
} catch (error) {
console.log('?? ~ Error', error)
}
}, [])
useEffect(() => {
getInitialData()
}, [getInitialData])
return <div>PromiseAll</div>
}
此處帶有 console.logObject { test3: Promise { "fulfilled" } }回圈的示例https://codesandbox.io/s/romantic-mendel-xm5jk9?file=/src/App.tsx
uj5u.com熱心網友回復:
聽起來你想要類似的東西
async function awaitNamedPromises(nameToPromise) {
const namesAndPromises = Object.entries(nameToPromise);
const promises = namesAndPromises.map(([, promise]) => promise);
const results = await Promise.all(promises);
return Object.fromEntries(namesAndPromises.map(([name, promise], index) => [name, results[index]]));
}
const results = await awaitNamedPromises({
test1: Promise.resolve('hello'),
test2: Promise.resolve('world'),
test3: Promise.resolve('bye'),
});
console.log(results);
這列印出來
{ test1: 'hello', test2: 'world', test3: 'bye' }
uj5u.com熱心網友回復:
通過使用其名稱創建外部物件但僅將 Promise 僅傳遞給 Promise 來解決。所有這些都是粗略的原型。
const getInitialData = useCallback(async () => {
try {
const api = [
{ name: 'test1', api: getTest1 },
{ name: 'test2', api: getTest2 },
{ name: 'test3', api: getTest3 },
]
const res = await Promise.all(api.map((el) => el.api))
for (let i = 0; i < res.length; i ) {
const el = res[i]
el.isError && console.log(`Error in ${api[i].name}`, el.isError)
const state = { [api[i].name]: el.isData }
console.log('?? ~ state', state)
}
} catch (error) {
console.log('?? ~ Error', error)
}
}, [])
Offcourse 我會使用一些 prevStatestate這樣以前的資料不會在每個回圈上被覆寫
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/454269.html
標籤:javascript 反应 打字稿 异步等待 es6-承诺
