【问题标题】:How to await data from async/await debounced axios call如何等待来自 async/await 去抖 axios 调用的数据
【发布时间】:2020-06-21 05:36:07
【问题描述】:

我正在尝试使用 lodash 的 debounce 函数从 API 请求中返回去抖动的搜索结果,但不断从调用中获取 undefined

这是我的代码,请帮忙;

const searchSuggestionsRequest = async (input) => {
  const params = {
   userInput: encodeURIComponent(input),
  };
   const { data } = await axios.get(`${BASE_URL}/api/location`, { params });
  return data;
};

 const debouncedSuggestionsRequest = _.debounce(searchSuggestionsRequest, 500);

 const fetchSearchSuggestions = (input) => {

 return debouncedSuggestionsRequest(input);
};

handleSearchSuggestions = async (input) => {
  const searchObj = await fetchSearchSuggestions(input);
  console.log('searchObj', searchObj);

 };


handleSearchSuggestions()

【问题讨论】:

    标签: javascript async-await axios lodash


    【解决方案1】:

    您期望 debounce 函数返回原始函数的结果,或者在您的情况下返回已解决的承诺。但这不是 debounce 函数的工作原理。

    debounce 函数用它自己的代码包装你的函数,它会检查我们的 not 中是否有任何新的调用文件。一段时间后,您的功能最终会启动。但它不能返回该函数的结果。

    您需要定义一个更全局的范围(或至少一个与您的函数重叠的范围)变量,并在您的函数中设置该变量以获取 axios 结果。

    你的问题仍然是你不能等待结果,所以你的 console.log 仍然是未定义的。我个人是在 Vue 中开发的,我可以在变量上设置一个反应性观察者。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-08-29
      • 1970-01-01
      • 2021-12-11
      • 2016-03-08
      • 1970-01-01
      • 1970-01-01
      • 2021-02-10
      相关资源
      最近更新 更多