Wait for response after clicking the button in Vue before proceeding

When the button is clicked for the first time and the data property is empty, I need to pause the button click code until an ajax response is received.

Currently, when I press the button, both wait and scroll actions happen immediately without 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>

Answer №1

Make sure to include the callback in your code because it is essential for awaiting the promise later on. Take a look at the example below, removing the return from a.then will help resolve the issue:

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()

To ensure functionality, add a return statement as shown below:

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;
            });
        }
    }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I retrieve the Google Maps URL containing a 'placeid' using AJAX?

I have a specific URL that I can access through my browser to see JSON data. The URL appears as follows: https://maps.googleapis.com/maps/api/place/details/json?placeid=ChIJZeH1eyl344kRA3v52Jl3kHo&key=API_KEY_HERE However, when I attempt to use jQuer ...

Stopping before destruction in Vue 2 Lifecycle phases - how is it done?

Is there a way to modify beforeDestroy in order to prevent the component from being destroyed? Alternatively, is there any method to halt the destruction process of the component? In my specific situation, I am switching SPA pages using Vue Router. Even ...

The JQuery mobile navigation menu effortlessly appears on your screen

I am experiencing an issue with a JQuery mobile navigation that is designed for screens @979 pixels wide. The problem arises when the screen is resized to 979px - the menu pops up fully extended and covers the content of the web page. I suspect that this ...

I'm seeking an easy method to adjust the x and y coordinates of a popup rectangle with a fixed size. Can anyone provide

Is there a way to create a simple pop-up rectangle, possibly using jQuery or a similar tool, that presents a scaled-down canvas view of a larger browser window (1000px x 1600px), allowing users to click and determine the x/y position within the full window ...

Show the chosen value from the dropdown menu on all JSP pages

I have a header.jsp file containing a dropdown box labeled "Role". This header.jsp is designed to be included in all other JSP files using a directive. Once a user logs in, they are directed to a homepage where they must select a value from the dropdown ...

Troubleshooting: jQuery's append function does not seem to be functioning properly when trying

I am attempting to include a stylesheet in the head section of my page, but it seems that using 'append' is not getting the job done. Is there an alternative approach I should consider? Here is the code snippet: $('head').append(&apos ...

Creating dynamic tables in Vue JS is a powerful feature that allows developers to generate

I have been trying to implement a button that, when clicked, will generate a new table. Unfortunately, my search for a solution has come up empty so far. Most tutorials I found focus on manipulating rows in a single table rather than creating a new one fro ...

What are the steps involved in converting a MERN application into a desktop application?

As a beginner in front-end application development, I recently created a MERN application in React with separate frontend and backend parts. Everything is working smoothly, but now I want to convert it into a desktop application that can run independently ...

Select box failing to display default value

I am dealing with a specific data structure: $scope.personalityFields.traveller_type = [ {"id":1,"value":"Rude", "color":"red"}, {"id":2,"value":"Cordial", "color":"yellow"}, {"id":3,"value":"Very Friendly", "color":"green"}, ]; Also, there is a se ...

Exploring the MEVN Stack's Integration with Image Uploading

After successfully implementing an image upload system on my website, I encountered difficulty in linking to the uploaded images. The root directory of my project includes a client folder for vuejs app and a server folder for backend logic. When users upl ...

Exploring the benefits of event subscription nesting

One feature I'm currently utilizing is the Angular dragula drag and drop functionality, which enables me to effortlessly move around Bootstrap cards within the view. When an item is "dropped," it triggers the this.dragulaService.drop.subscribe() funct ...

Looking to receive child events within a Vue 3 setup()?

Looking to convert the code below to use Vue 3 composition API. I am trying to listen for an event from a child component in a parent component that utilizes the render function. In Vue 3, $on has been removed and I'm unsure of how to replace it in t ...

Clicking to close tabs

I am currently working on implementing a tab functionality on my website and I want these tabs to be responsive. Here is the code snippet I have been using: function openCity(evt, cityName) { var i, tabcontent, tablinks; tabcontent = document.ge ...

Tips for swapping out a div tag with another div tag in the same spot without needing to redirect to a different page by utilizing bootstrap

Currently, I am developing a JSP project that utilizes Bootstrap for the frontend. I have come across a question regarding HTML design. Is there a way to replace one div tag with another div on the same page without navigating to a new URL using Bootstrap ...

Koa.js route() isn't a defined function

Recently, I created a basic koa app that should return rss xml based on a tag using a parameter. However, for some reason the middleware is unable to read the router from the router file and I cannot figure out why it's not working as expected. The ap ...

How can you establish an environmental variable in node.js and subsequently utilize it in the terminal?

Is there a way to dynamically set an environmental variable within a Node.js file execution? I am looking for something like this: process.env['VARIABLE'] = 'value'; Currently, I am running the JS file in terminal using a module whe ...

Is there a tool or software available that can securely encode a text file into an HTML file without the need for loading it using AJAX?

At the moment, I'm using jQuery to load a txt file (in utf-8) via $.ajax. The txt file has some break lines, such as: line1 line2 line3 When loaded through AJAX into a variable, it appears as: line1\n\nline2\nline3 I could manuall ...

Executing a function in Node-Express with a database connection at the beginning of the application

I am relatively new to Node.js and currently working on a Node.js - Express solution as a back-end for an AngularJS web application. My goal is to send an email when the MSSQL database query returns specific information. I have successfully implemented thi ...

"Exploring the incredible powers of Ionic2, Angular2, HTTP requests, and

Despite all the research I've done on observables, I still struggle to grasp how they function. The HTTP request code snippet is as follows: import { Component, OnInit, Injectable } from '@angular/core'; import { Http, Response, Headers, R ...

Performing date comparison in JavaScript with varying date formats

My system includes a table that retrieves dates from an FTP location. On the user interface page, there is a form that gathers all details related to a specific FTP date. However, I am facing difficulties in comparing the FTP dates with those specified in ...