简体   繁体   中英

How to await data from async/await debounced axios call

I'm trying to return a debounced search result from an API request using lodash's debounce function but keep getting undefined from the call.

Here's my code, please help;

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

You are expecting the debounce function to return the result of your original function, or in your case the resolved promise. But that is not how the debounce function works.

The debounce function wraps your function with its own code in which it checks if any new call files in our not. After a certain amount of time eventually your function is initiated. But it cannot return the result of that function.

You need to define a more global scope (or at least a scope overlapping your functions) variable, and set that variable in your function where you get the axios result.

You problem remains that you cannot await for the result, so your console.log will still be undefined. Personally I develop in Vue, and I can set a reactivity watcher on the variable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM