0

I have a vue function call which is triggered when selecting a radio button but it seems that my code inside my $nextTick is running before my previous line of code is finished. I don't want to use setTimout as I don't know how fast the user connection speed is.

findOrderer() {
    axios.post('/MY/ENDPOINT')
        .then((response) => {
            this.orderers = response.data.accounts;

            console.log('FIND_ORDER',  this.orderers)

            ...OTHER_CODE
}

rbSelected(value) {
    this.findOrderer();
    this.newOrderList = [];

    this.$nextTick(() => {
        for (var i = 0, length = this.orderers.length; i < length; i++) {
            console.log('FOR')

            if (value.srcElement.value === this.orderers[i].accountType) {
                console.log('IF')

                this.newOrderList.push(this.orderers[i]);
            }
        }

        this.$nextTick(() => {
            this.orderers = [];
            this.orderers = this.newOrderList;

            console.log('orderers',this.orderers)
        })
    })
}

Looking at the console log the 'FINE_ORDERER' console.log is inside the 'findOrderer' function call so I would have expected this to be on top or am I miss using the $nextTick

enter image description here

murday1983
  • 3,806
  • 14
  • 54
  • 105

1 Answers1

0

That's expected, since findOrderer() contains asynchronous code. An easy way is to simply return the promise from the method, and then await it instead of waiting for next tick:

findOrderer() {
    return axios.post('/MY/ENDPOINT')
        .then((response) => {
            this.orderers = response.data.accounts;
            console.log('FIND_ORDER',  this.orderers);
        });
},

rbSelected: async function(value)  {

    // Wait for async operation to complete first!
    await this.findOrderer();

    this.newOrderList = [];

    for (var i = 0, length = this.orderers.length; i < length; i++) {
        console.log('FOR')

        if (value.srcElement.value === this.orderers[i].accountType) {
            console.log('IF')

            this.newOrderList.push(this.orderers[i]);
        }
    }


    this.orderers = [];
    this.orderers = this.newOrderList;

    console.log('orderers',this.orderers)
}
Terry
  • 63,248
  • 15
  • 96
  • 118
  • Still getting the same issue, the code is running before the asynchronous code finished. basically then `this.orderers = []` it empties it and then re-pops with the new `array` but on screen, as this is running before the `axios` stuff finished, my list quickly displays my new list then re-pop's with the original details and this is the case using your proposed fix – murday1983 Jul 01 '20 at 14:41
  • @murday It is not running before the axios request is complete because we are awaiting the promise’s resolution. So I’m not sure what you’re want to achieve. – Terry Jul 01 '20 at 19:10