0

I can't work out how to return the nested .then methods, and resolve the value to the function that called it?

I can print it, at the deepest level of the last .then(), but I would like to print the returned value in the event listener.

  connectedCallback () {
    this.input.addEventListener('input', event => {
      this.search(this.input.value)
    })
  }

  search (str) {
    let searchResult = window.fetch(`http://localhost:3000/api/?q=${str}`)
      .then(result => {
        return result.json()
          .then(result => {
            return result
          })
      })
  }
}
Jebiel
  • 52
  • 6
gideonen
  • 53
  • 2
  • 8
  • 1. don't nest, just use the Promise API to get a flat chain going 2. return the last promise and use it in that calling function. – VLAZ Dec 05 '19 at 16:22
  • I was browsing through it but I did not manage to translate it to my problem. How do I do that? – gideonen Dec 05 '19 at 16:23

1 Answers1

2

Use async/await to await the promise result in the event listener. You can also simplify your promise chain considerably:

  connectedCallback() {
    this.input.addEventListener("input", async event => {
      const result = await this.search(this.input.value);
      console.log(result);
    });
  },

  search(str) {
    return window
      .fetch(`http://localhost:3000/api/?q=${str}`)
      .then(result => result.json());
  }

I would recommend reading up on promises and getting familiar with how they work.

James Coyle
  • 9,922
  • 1
  • 40
  • 48
  • Thank's, I was wondering more specifically about `.then()` i have used async previously but would like to understand this method – gideonen Dec 05 '19 at 16:34
  • It just lets you take the result from the previous promise and returns a new promise which resolves to the result returned by the function you pass it. In this case you take the result from the fetch promise and convert it to json which is then returned as the result of another promise so you can add additional `.then()` calls. Think of it as queueing up functions to run in a chain once an async operation completes. – James Coyle Dec 06 '19 at 00:00