3

I have a function need to write async but I can't do it the right way. How can I achieve this?

async search (loading, search, vm) {
  let vm = this
  _.debounce(() => {
    let ApiURL = '/users/'
  }

  let { res } = await api.get(ApiURL) //Error
    vm.options = res.data
  }, 800)
halfer
  • 19,824
  • 17
  • 99
  • 186
KitKit
  • 8,549
  • 12
  • 56
  • 82
  • 1
    don't use `then()` with `async`. You already have `res` you don't need to use `then()` to get it. – Mark May 19 '18 at 07:18
  • Fixed it. error in `await` line, bro – KitKit May 19 '18 at 07:19
  • Does this answer your question? [How can I debounce using async/await?](https://stackoverflow.com/questions/44501653/how-can-i-debounce-using-async-await) – mikemaccana Mar 07 '22 at 17:06
  • [Assigning the debounce function to a variable](https://stackoverflow.com/questions/42199956/how-to-implement-debounce-in-vue2/49780382#49780382) should do the trick – Stetzon Jun 24 '22 at 14:43

2 Answers2

10

You should avoid using the debounce function provided by Lodash when dealing with promises since it doesn't distinguish sync and async function and works like if the function you fed it was synchronous. So it doesn't wait till the promise is resolved or rejected and returns immediately. This means that the time spent for, say ajax request, doesn't count towards function execution time, and in case of network delay it's possible for the responses to come in different order.

I suggest to pick up the awesome-debounce-promise on npm.

4

Just assign the lodash function directly as a component method

new Vue({
    el: '#app',
    data: { requests: 0 },


  methods: {
    search: _.throttle(async function () {  
      const res = await fetch('/echo/json/')
      this.requests++
      console.log(res)
    }, 1000)
  },


  created () {
    // 100ms interval but throttle works at 1000ms
    setInterval(() => {
        this.search()
    }, 100)
  }
})

https://jsfiddle.net/6thcxfym/

In your case:

methods: {
    search: _.debounce(async function () {
      // this code may differ from your actual implementation
      const res = await api.get('/users/')
      this.options = res.data
    }, 1000)
  }
}
Frondor
  • 3,466
  • 33
  • 45
  • Thanks for the downvote. Votes are meant for differentiating an answer from the rest, and for those that don't actually answer the OP question. None of that is the case at the moment of writing this comment. I implemented your suggestion though, thanks. – Frondor May 19 '18 at 12:46
  • 1
    There's no real rules around voting honestly. I thought your original answer was poor given the alternatives and posted an example to show how you might improve it. Now that you've done that, I'm removing the downvote and upvoting. – Bert May 19 '18 at 12:48
  • 2
    Thank you Frondor. Your solution is okay – KitKit May 21 '18 at 03:53