【问题标题】:Using async/await, array.length still shows as 0 [closed]使用 async/await,array.length 仍显示为 0 [关闭]
【发布时间】: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


【解决方案1】:

你不应该在你的代码中包含括号,因为这样renderAutoComplete函数会在解决promise之前被调用。你应该只放一个函数,让Promise机制在它完成后调用它。

search(input).then( val => results.push(...val)).then(renderAutoComplete);

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-08
    • 1970-01-01
    • 2019-04-22
    • 2020-10-02
    • 2017-06-30
    • 2019-05-29
    • 2016-06-13
    • 1970-01-01
    相关资源
    最近更新 更多