【问题标题】:Multiple nested axios calls don't resolve as expected多个嵌套的 axios 调用未按预期解决
【发布时间】:2021-07-06 21:46:03
【问题描述】:

正如我的代码 sn-p 之间的 cmets 中所述,异步未按预期工作。对于每个id,应该返回一个对象/项目,但它只返回一个项目,因为我的async await 没有正确实现。有什么可能的解决方法?

提前致谢

useEffect(() => {
    axios.get('url-here').then((res) => {
      res.data.favProperties?.map((el) => {
        console.log(el) // this returns multitple id's of saved/liked items
        axios.get('url-here').then(async (r) => {
          if (r.data) {
            console.log(r.data) // Problem starts here
            // This returns the full object of the liked items
            // But only one object is returned, not every object for which an id was stored
            await storageRef
              .child(r.data.firebaseRef + '/' + r.data.images[0])
              .getDownloadURL()
              .then((url) => {
                // Here i need to fetch the image for each object
                console.log(url)
              })
              .catch((err) => console.log(err))
          }
        })
      })
    })
  }, [])

【问题讨论】:

  • 这似乎是在 useEffect 钩子中调用的奇怪代码,也许包含组件的更多细节将有助于定义您要执行的操作。
  • 除了上面@ScottGnile 所说的内容之外,您可能应该使用async/await,因为这会提高代码的易读性,从而增加维护和错误修复。
  • 嗯,我正在使用async await 并尝试了很多不同的东西,但没有任何效果。我怎样才能正确地实现async await
  • @ScottGnile 我应该在哪里以及如何拨打电话?
  • @brunelli 您可以在此处阅读有关如何将代码迁移到异步/等待的信息stackoverflow.com/a/55272812/1816108

标签: reactjs asynchronous async-await axios


【解决方案1】:

我认为将您的操作分解为函数可以防止这种 Promise Hell。我建议使用 async await 进行这些操作。此外,我对控制台记录下载 URL 的最后一部分感到困惑,我猜您正在尝试将这些 喜欢的项目 的所有 下载 URL 保存在一个数组中。

    useEffect(() => {
      firstFunction();
    }, []);

    const firstFunction = async () => {
    const { data } = await axios.get("url-here");
    const favProperties = data.favProperties;
    const fetchedUrls = await Promise.all(
        favProperties?.map(async (el) => (
          await secondFunction(el.id) /** use el to pass some ID */
        ))
      );
    };
  
    const secondFunction = async (someId) => {
      /** your second URL must point to some ID (or some parameters) specific API otherwise
 running same op in a loop without variations doesn't make any sense */
      const { data } = await axios.get(`some-other-url/${someId}`);
      if (data) {
        console.log(data);
        const fetchedUrl = await storageThing(data);
        return fetchedUrl;
      }
    };
    
    const storageThing = async ({ firebaseRef, images }) => {
      try {
        const downloadURL = await storageRef
          .child(firebaseRef + "/" + images[0])
          .getDownloadURL();
        console.log(downloadURL);
         return downloadURL;
       } catch (error) {
         console.log(error);
         return '';
       }
     };

【讨论】:

  • 非常感谢您的详细回答。问题是,我的代码一直在工作,但我预期的结果不同,因为还有另一个问题(错误的id's 存储在数据库中,因此不可能返回多个objects)。不过,我将来可以使用此代码,因为它是async await 的一个明显示例。再次感谢
猜你喜欢
  • 2018-06-06
  • 1970-01-01
  • 2020-02-04
  • 1970-01-01
  • 2019-01-22
  • 1970-01-01
  • 1970-01-01
  • 2012-11-18
  • 1970-01-01
相关资源
最近更新 更多