Write async function with Lodash in a Vuejs component

后端 未结 2 1936
攒了一身酷
攒了一身酷 2021-01-15 21:12

I have a function need to write async but I can\'t do it the right way. Hope your guys help.

async search (loading, search, vm) {
  let vm = this
  _.debounc         


        
相关标签:
2条回答
  • 2021-01-15 21:27

    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)
      }
    }
    
    0 讨论(0)
  • 2021-01-15 21:47

    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.

    0 讨论(0)
提交回复
热议问题