【问题标题】:How to get fetch api results in execution order with async/await?如何使用 async/await 按执行顺序获取 fetch api 结果?
【发布时间】:2020-01-28 19:55:13
【问题描述】:

在我的输入元素中发生输入更改后,我运行一个空字符串检查 (if (debouncedSearchInput === "")) 以确定我是获取一个 api 还是另一个。

主要问题是正确的promise比另一个更快返回,导致渲染数据不正确。

    //In my react useEffect hook
        useEffect(() => {
           //when input empty case
           if (debouncedSearchInput === "") autoFetch();
           //search
           else searchvalueFetch();
        }, [debouncedSearchInput]);

当我清空输入时,searchvalueFetch() 返回的速度比 autoFetch() 慢。我得到了延迟的 searchvalueFetch() 数据,而不是正确的 autoFetch() 数据。

有什么方法可以解决这个问题?如何排队从 Promise 中返回?

我读了Reactjs and redux - How to prevent excessive api calls from a live-search component? 但是

1) 承诺部分让我感到困惑

2) 我认为我不必使用类

3) 我想了解更多异步/等待

编辑:添加searchvalueFetchautoFetchfetcharticles 代码

  const autoFetch = () => {
    const url = A_URL
    fetchArticles(url);
  };
  const searchNYT = () => {
    const url = A_DIFFERENT_URL_ACCORDING_TO_INPUT
    fetchArticles(url);
  };
  const fetchArticles = async url => {
    try{
      const response = await fetch(url);
      const data = await response.json();
      //set my state
    }catch(e){...}
  }

【问题讨论】:

  • 您发布的代码似乎没有使用 Promise 或 fetch - 请显示您遇到问题的代码
  • 我刚刚添加了更多

标签: javascript reactjs promise async-await


【解决方案1】:

这是一个想法。您可以使用承诺来实现这一目标。首先将调用autoFetch,然后调用searchvalueFetch

   useEffect(() => {
     const fetchData = async () => {
       await autoFetch();
       await searchvalueFetch();
     };

     fetchData();

   }, []);

【讨论】:

    【解决方案2】:

    您还可以在任何生命周期中使用函数,具体取决于您的项目。

    lifecycle(){
         const fetchData = async () => {
    try{
           await autoFetch();
           await searchvalueFetch();
    } catch(e){
    console.log(e)
    }
         };
    
         fetchData();
    
       }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-08-14
      • 2019-07-01
      • 2020-08-16
      • 2018-12-15
      • 2021-09-02
      • 2020-09-28
      • 2021-09-30
      • 1970-01-01
      相关资源
      最近更新 更多