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

发布于 2025-01-18 07:08:00 字数 808 浏览 2 评论 0原文

我现在通过了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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

甜`诱少女 2025-01-25 07:08:00

听起来你想要这样的东西

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

Sounds like you want something like

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);

This prints out

{ test1: 'hello', test2: 'world', test3: 'bye' }
影子是时光的心 2025-01-25 07:08:00

通过使用其名称创建外部对象但仅将 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('

Solved by creating outside object with it's name but only passing Promise only to Promise.all this is rough prototype.

  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 i would use something prevState on state so the previous data won't be overridden on each loop

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文