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

Error in linking PHP code to display stored tweets using HTML code

![enter image description here][1]![image of output of twitter_display.php][2] //htmlsearch.html file <!doctype html> <html> <head> <title>Twitter</title> <meta charset="utf-8"> <script> window.onload = function ...

Tips for controlling numerous tabSlideOUt tabs on a single webpage

Is there a way to implement multiple tabSlideOut functionalities on a single page, similar to the examples provided in the following links: source code on GitHub and Fiddle Example? Specifically, I am looking to have tabs that can be toggled, ensuring tha ...

Tips for maintaining the nested QRouteTab to stay alive (Vue.js 3 with Quasar 2)

Struggling to create a user interface with 2 nested tabs (check out the screenshot), where all visited panels remain active. I've put together a small example here: https://codesandbox.io/s/no-keep-alive-b7x2sj The issue I'm facing is that only ...

Persistent button positioned at the bottom of the page, remaining visible even when scrolling to the very end of the content

I am looking to add a floating button that remains in the same position relative to the content until the window is scrolled to a certain point, after which it sticks to the end of the content. In simple terms, I want the element to act as 'relative& ...

Tips for resolving the issue of receiving a warning about passing "onClick" to a "<Link>" component with an `href` of `#` while having "legacyBehavior" enabled in Next.js

My current project is displaying a lot of warnings in the browser console and I'm unsure about the reasons behind it. The warnings include: "onClick" was passed to with href of /discovery/edit but "legacyBehavior" was set. The l ...

Rails - removing list item upon deletion of parent object

Currently working on a project app as part of a full stack developer bootcamp program. One of the features I'm implementing is a destroy method to remove an item from a list. Using AJAX requests, the goal is to dynamically remove the li element repres ...

Image not appearing when sharing on Facebook

I've been trying to create a Facebook share button using the Javascript SDK, and here is the code I have been utilizing: $(function() { $('.facebook-share').click(function(e) { e.preventDefault(); FB.ui({ method: 'feed& ...

Experiencing a problem during the installation of npm express for testing purposes

Having trouble installing supertest as I keep receiving errors in the terminal. When I run 'supertest -v', it says command not found. Even after installing, I encounter the following error. Any suggestions would be greatly appreciated. I attempte ...

Utilize webpack to import functions from separate files

I am looking to streamline the process of importing and using functions from a different file. Ideally, I would like to simply call these functions by their name without any extra prefixes or naming conventions. However, I am aware that using eval() can po ...

Repositioning a variable number of divs as the cursor hovers over the target area

Can anyone show me how to generate div elements in a loop using jQuery and change their position with the "mouseover" function? I've tried some code, but the positioning isn't changing correctly. Any suggestions on what needs fixing? var r, g, ...

Is there a way to set the default timezone for the entire application to something like 'UTC' using JavaScript and Angular?

I'm currently developing a Hotel application where customers communicate using UTC. I have completed most of the work but everywhere I used the date object like so => new Date(). Before running the application, I need to change my local timezone to ...

Improving an unspecified JavaScript function

After taking inspiration from another website, I incorporated this code snippet into my project, only to find that it's not functioning properly. What could be the issue? var LessonsCustomControl = (function LessonsCustomControl_constructor(){ va ...

Transforming Exposed components (jQuery Tools)

I need to toggle between two elements, exposing one while hiding the other with a single onClick event. Can this be achieved? My current JavaScript code does not seem to work as intended. Here is my existing script: function tutStep1(){ jQuery(' ...

Display or conceal various objects using a single button in HTML

I've been working on creating a chatbot widget for my website, but I've run into an issue. The "Chat with us" button only shows the bot and not the close button as well. Here's what I've attempted: <input id="chat" type="button" on ...

Issue encountered while utilizing PHP sessions

I'm currently developing a basic login page that utilizes JS, JQuery, and PHP. login.php <!DOCTYPE html> <head> <title>AJAX Login Learning Activity</title> <link rel="stylesheet" type="text/css" href="login.css"> ...

The deletion was not successfully carried out in the ajax request

Can anyone help with an issue I'm having while trying to remove a row from a table using the closest function? The function works fine outside of the $.post request, but it doesn't work properly when used within the post request. Here is my code: ...

Retrieve the selected date from the date picker widget

Welcome to my custom datepicker! Here is the HTML code: <div class="field-birthday field-return" id="birthday-edit" style="display:none;"> <div class="birthdaypicker"></div> <input class="hidden" name="birthday" type="hidden" ...

Transform an array of integers into a mapping of values and corresponding IDs for selected values

I've been able to successfully load values from my API into react-select for single select, but I'm encountering some issues with multi-select. const fetch_companies = () => { API.get("/companies") ... data = data.map(({ id: ...

Using jQuery to select elements with specific innerHTML values

$('.select option:selected[innerHTML="5"]') In this case, I am attempting to choose an option that is currently selected and has innerHTML that perfectly matches a specific string (for example: "5") For reference, here is a fiddle link: http:// ...

What is the process for showcasing specific Firestore items on a webpage?

database I've encountered an intriguing bug in my code that is proving difficult to resolve. The code involves a straightforward setup with React and Firestore, where items are listed on one page and their details are displayed on the next. However, t ...