Martyn Ball
Martyn Ball

Reputation: 4895

Vue, button click wait for response before continuing

if my button is clicked for the first time, so a data property is empty, I want to wait for a ajax response before continuing with the button click code.

At the moment when I hit the button I get wait and scroll straight away so it's not waiting for the response.

<template>
    <div class="FinanceSlider">
        <div class="BudgetSlider">
            <div class="ShowPayments">
                <a href="javascript:void(0)"
                   @click="focus"
                   class="btn--secondary"
                   title="See my payments">
                    <span class="ci-spinner spin" v-if="loading"></span>See my payments
                </a>
            </div>
        </div>
    </div>
</template>

<script>
import Axios from "axios";

export default {
    data () {
        return {
            quote: null
        }
    },
    methods: {
        focus: async function () {

            // Wait for a quote before scrolling to it.
            if (!this.quote) {
                console.log('wait');
                await this.getQuote();
            }

            // Already has data, scroll to it.
            console.log('scroll')
        },
        getQuote: function() {
            this.loading = true;
            Axios.post('credit-calculator/calculate', {}).then(response => {
                this.loading = false;
                if (response.data) {
                    window.EventBus.$emit('finance-calculator-display', response.data);
                }
                return true;
            });
        }
    }
}
</script>

Upvotes: 0

Views: 1533

Answers (1)

Satyam Pathak
Satyam Pathak

Reputation: 6932

You need to return the callback as it is the promise which is needed to be awaited later. See the following snippet, remove the return from a.then at it will behave similarly to your problem

function foo() {
  const a = new Promise((res, rej) => {
    setTimeout(() => { console.log('2'); res(1)}, 1000)
  })
  
  return a.then(e => {
    console.log('print 3')
  })
}

async function bar() {
 console.log('print 1')
 await foo()
 console.log('print 4')

}

bar()

See below I have added a return and it should work

methods: {
        focus: async function () {

            // Wait for a quote before scrolling to it.
            if (!this.quote) {
                console.log('wait');
                await this.getQuote();
            }

            // Already has data, scroll to it.
            console.log('scroll')
        },
        getQuote: function() {
            this.loading = true;
            return Axios.post('credit-calculator/calculate', {}).then(response => {
                this.loading = false;
                if (response.data) {
                    window.EventBus.$emit('finance-calculator-display', response.data);
                }
                return true;
            });
        }
    }

Upvotes: 1

Related Questions