动态解析每个API调用的Promise.all响应并存储数据



我现在将3个API调用传递给Promise.all。目前,对于每个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

听起来你想要这样的东西

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' }

通过创建具有其名称的外部对象来解决,但只将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)
}
}, [])

当然,我会在state上使用prevState,这样之前的数据就不会在每个循环上被覆盖

最新更新