动态解析每个 API 调用的 Promise.all 响应并存储数据
我现在通过了3个API呼叫。目前,对于每个API调用,我需要创建单独的错误处理程序,并且是否正在将数据返回到其自己的对象(对应于同一API对象名称)。
如果我将test4
传递给Promise。所有这些如何使其能够生成自己的错误并将数据存储到状态对象,而不是我手动添加这些值?
我尝试了响应循环,但是获得对象{test3:promise {“ exhield”}}}
且无数据。
代码:
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('
I'm passing right now 3 API calls to Promise.all. For now for each API call i need to create separate Error handler and if data is being return store to it's own object (corresponding to same API object name).
If i pass test4
to Promise.all how can i make it generate it's own error and storing data to state object, instead of my manually adding those values?
I have tried loop the response but getting Object { test3: Promise { "fulfilled" } }
and no data.
Code:
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>
}
Example here with console.log Object { test3: Promise { "fulfilled" } }
in loop https://codesandbox.io/s/romantic-mendel-xm5jk9?file=/src/App.tsx
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
听起来你想要这样的东西
这打印出来
Sounds like you want something like
This prints out
通过使用其名称创建外部对象但仅将 Promise 传递给 Promise 来解决。所有这些都是粗略的原型。
Solved by creating outside object with it's name but only passing Promise only to Promise.all this is rough prototype.
Offcourse i would use something prevState on
state
so the previous data won't be overridden on each loop