Javascript 使用async/await时,array.length仍显示为0

Javascript 使用async/await时,array.length仍显示为0,javascript,promise,async-await,Javascript,Promise,Async Await,My异步/等待功能: async function search(pattern) { const res = await axios.get("/api/searchIndex.json"); const index = res.data; const options = { keys: ["title", "content"], shouldSort: true, th

My
异步/等待功能:

  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
函数。您应该只放置一个函数,让
Promise
机制在完成后调用它

search(输入)。然后(val=>results.push(…val))。然后(renderAutoComplete)

另外,我建议将
renderAutoComplete
函数更改为接受
results
作为参数,而不是使用全局变量

function renderAutoComplete (results) {
...
}
...
search(input).then(renderAutoComplete);

在承诺解决之前,您正在调用
renderAutoComplete
search(输入)。然后(val=>results.push(…val))。然后(renderAutoComplete())
->
search(输入)。然后(renderAutoComplete)
。实际上甚至不需要声明
结果
,只需将
val
数组作为参数隐式传递给
renderAutoComplete
,而不是将
renderAutoComplete()
的返回值传递给
then()
,传递函数引用-->
then(renderAutoComplete)
duplicate: