我正在尝试使用 lodash 的去抖动功能从 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()
1 回答

神不在的星期二
TA贡献1963条经验 获得超6个赞
您期望该debounce
函数返回原始函数的结果,或者在您的情况下返回已解决的承诺。但这不是 debounce 功能的工作方式。
debounce 函数用它自己的代码包装你的函数,它会检查我们的 not 中是否有任何新的调用文件。一段时间后,您的功能最终会启动。但它不能返回该函数的结果。
您需要定义一个更全局的范围(或至少与您的函数重叠的范围)变量,并在您获得 axios 结果的函数中设置该变量。
你的问题仍然是你不能等待结果,所以你的 console.log 仍然是未定义的。我个人是在 Vue 中开发的,我可以在变量上设置一个反应观察者。
添加回答
举报
0/150
提交
取消