1

My async/await function:

  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);
  }

Where it's called, and then I push the object to an array results and then execute renderAutoComplete

function handleSearchInput(event) {
  input = event.target.value;
  if (input.length >= 3) {
    results =[];
    showAutoComplete = true;
    search(input).then( val => results.push(...val)).then(renderAutoComplete());
  }
}

But, in renderAutoComplete results always equals 0 and I can't access the data. So this means I have an issue somewhere in my async/await. Of course, if I console.log I get: array console log

Jason
  • 7,612
  • 14
  • 77
  • 127
  • 3
    you are calling `renderAutoComplete` _before_ the promise resolves. – Daniel A. White Aug 24 '20 at 17:42
  • 4
    `search(input).then( val => results.push(...val)).then(renderAutoComplete())` -> `search(input).then(renderAutoComplete)`. There's really no need to even declare `results`, just let your `val` array be passed implicitly as a parameter to `renderAutoComplete` – Patrick Roberts Aug 24 '20 at 17:42
  • 1
    Instead of passing the return value of `renderAutoComplete()` to `then()`, pass the function reference --> `then(renderAutoComplete)` – Yousaf Aug 24 '20 at 17:44
  • 1
    duplicate: https://stackoverflow.com/questions/43644230/then-callback-firing-before-promise-is-resolved-in-node-js – Klaycon Aug 24 '20 at 17:44

1 Answers1

1

You shouldn't include brackets in your code, because in that manner renderAutoComplete function will be called before resolving the promise. You should put just a function and let Promise mechanism call it when it's finished.

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

Also I would recommend to change renderAutoComplete function to accept results as an argument instead of using a global variable.

function renderAutoComplete (results) {
...
}
...
search(input).then(renderAutoComplete);
szatkus
  • 1,292
  • 6
  • 14