【发布时间】:2020-08-24 17:40:55
【问题描述】:
我的async/await 功能:
async function search(pattern) {
const res = await axios.get("/api/searchIndex.json");
const index = res.data;
const options = {
keys: ["title", "content"],
shouldSort: true,
threshold: 0.5,
maxPatternLength: 50
};
const fuse = new Fuse(index, options);
return fuse.search(pattern);
}
在哪里调用,然后我把对象推到数组results然后执行renderAutoComplete
function handleSearchInput(event) {
input = event.target.value;
if (input.length >= 3) {
results =[];
showAutoComplete = true;
search(input).then( val => results.push(...val)).then(renderAutoComplete());
}
}
但是,renderAutoComplete results 总是等于 0,我无法访问数据。所以这意味着我在async/await 的某个地方有问题。
当然,如果我 console.log 我得到:
【问题讨论】:
-
你正在调用
renderAutoComplete在承诺解决之前。 -
search(input).then( val => results.push(...val)).then(renderAutoComplete())->search(input).then(renderAutoComplete)。甚至不需要声明results,只需让您的val数组作为参数隐式传递给renderAutoComplete -
不是将
renderAutoComplete()的返回值传递给then(),而是传递函数引用 -->then(renderAutoComplete)
标签: javascript promise async-await