Execute a Vue.js script once all Axios calls have been resolved

In this scenario, it is necessary to execute the carResult function only after all axios requests have been completed. Placing it inside the success method of method2 won't work because the component ends up executing the code twice. It would be greatly appreciated if someone could provide a Vue code snippet that executes after all axios requests are finished.

<html>
    <head>
        <title>title</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </style>
</head>
<body>
    <div id="el">
        <div>
            <p>Selected: {{ input.selected }}</p>
            <select2 :options="options" v-model="input.selected">
                <option disabled value="0">Select one</option>
            </select2>
        </div>
        <div>
            <p>Selected: {{ input.selected2 }}</p>
            <select2 :options="options2" v-model="input.selected2">
                <option disabled value="0">Select one</option>
            </select2>
        </div>
    </div>
    <script type="text/x-template" id="select2-template">
        <select>
        <slot></slot>
        </select>
    </script>
    <script src="http://themestarz.net/html/craigs/assets/js/jquery-3.3.1.min.js"></script>
    <script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7701021237455942594640">[email protected]</a>/dist/vue.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.min.js"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <script>
Vue.component('select2', {
    props: ['options', 'value'],
    template: '#select2-template',
    mounted: function () {
        var vm = this;
        $(this.$el)
                // init select2
                .select2({data: this.options})
                .val(this.value)
                .trigger('change')
                // emit event on change.
                .on('change', function () {
                    vm.$emit('input', this.value)
                })
    },
    watch: {
        options: function (options) {
            // update options
            $(this.$el).empty().select2({data: options})
        },
        value: function (value) {
            // update value
            $(this.$el)
                    .val(value)
                    .trigger('change')
        }
    },
    destroyed: function () {
        $(this.$el).off().select2('destroy')
    }
});

var vm = new Vue({
    el: '#el',
    data: {
        input: {
            selected2: "all",
            selected: "all"
        },
        options: [],
        options2: [],
        items: []
    },
    created: function () {
        this.mymethod();
    },
    watch: {
        input: {
            handler(newInput) {
                this.carResult(); 
            },
            deep: true
        },
        itemsArray() {
            this.setPages();
        }
    },
    methods: {
        mymethod: function () {
            var vm = this;
            axios.get('https://api.coindesk.com/v1/bpi/currentprice.json')
                    .then(function (response) {
                        vm.options = [
                            {id: 0, text: 'All'},
                            {id: 1, text: 'Hello'},
                            {id: 2, text: 'World'},
                            {id: 3, text: 'Bye'}
                        ];
                        vm.input.selected = 2;
                        vm.method2();
                    })
                    .catch(function (error) {
                        console.log(error);
                    });
        },
        method2: function () {
            var vm = this;
            axios.get('https://api.coindesk.com/v1/bpi/currentprice.json')
                    .then(function (response) {
                        vm.options2 = [
                            {id: 0, text: 'All'},
                            {id: 1, text: 'This'},
                            {id: 2, text: 'is'},
                            {id: 3, text: 'second'}
                        ];
                        vm.input.selected2 = 2;
                    })
                    .catch(function (error) {
                        console.log(error);
                    });
        },
        carResult: function () {
            var vm = this;
            axios.get('https://api.coindesk.com/v1/bpi/currentprice.json')
                    .then(function (response) {
                        vm.items = response.data;
                    })
                    .catch(function (error) {
                        console.log(error);
                    });
        }
    }
});
    </script>
</body>
</html>

Answer №1

Make sure to pass all your axios requests to Promise.all() function, which will only resolve once all the axios calls have been completed.

Promise.all([axios.get(url1), axios.get(url2), axios.get(url3)])
  .then((allResults) => {
    console.log("All the axios requests have been made!")
})

The Promise.all() function requires an array of promises as its argument, and each call to axios.get() method returns a promise.

All the values returned by Promise.all() will maintain the order of the Promises passed, regardless of their completion order.

For more information, check out: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

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

Encountering an issue when trying to upload a file for the second time

I am currently working on a project where I need to upload an excel file and send it to an API using ReactJS. So far, I have been able to successfully send the file to the API. However, in my submit function, I want to reset the saved excel file from the s ...

Is there a way to emphasize a particular day on the calendar obtained from the URL?

I have implemented FullCalendar functionality to enable users to select a specific date, retrieve data from a database, and then reload the page with that data. The page is updated with the selected date in the URL. However, when the page reloads, althoug ...

Ways to switch between Vue components

My main App.vue file contains elements like the navigation bar, with the rest of the content rendered by vue-router. I'm attempting to add a series of modals to this file so that they can be accessed from any route when clicking on the corresponding l ...

Implementing automatic line breaks in Bootstrap

When setting the "overflow scroll able" option, I want it to only allow scrolling in the y direction and if x content overflows, a line break should occur. I tried applying 'white-space', but it didn't work as expected. <ul class="s ...

The AJAX call is not being identified correctly

I am facing an issue with my search result pagination wherein the page reloads instead of loading via AJAX when using the pagination. The search results are correctly loaded through partial view with AJAX, but the pagination triggers a non-ajax request cau ...

Sorting through an array using a different array of values

Looking to filter one array with another, where values in the first array should match 'id' in the second array for filtering. The arrays in question are: const array1 = [a, b, c, d] The array to be filtered based on matching 'id' va ...

designing a presentation with customizable durations for each slide

I am trying to implement a slideshow using the slides.js jquery plugin and I have a specific requirement for the duration of each slide. My goal is to have the first slide, which contains an embedded video, display for 7 seconds, while the subsequent slid ...

Issue with Titanium: Unable to scroll within tableview

The tableview is not scrolling as expected. I tested it on a mobile device and the scrolling worked fine, but it doesn't seem to work on tablets. Please assist. CODE var win = Titanium.UI.createWindow({ title : 'Medall app', back ...

What is the best method for inserting a 'Placeholder' in an Angular datePicker?

Looking for assistance with placing placeholder text inside an Angular datePicker, specifically wanting to display 'From' and 'To' labels within the datePicker. datePicker I am a novice when it comes to Angular development - can someon ...

Oops! The program encountered an issue where it was unable to access the properties of an undefined variable, specifically while trying to

When creating a custom validation function in Angular, I encountered an issue where using a variable within the validation would result in an error: "ERROR TypeError: Cannot read properties of undefined (reading 'file')". This occurred when chang ...

The Dropdown Button Functions Once and Then Stops

I am facing a challenge in implementing a button within an HTML table that triggers a dropdown menu when clicked, and closes upon another click or when the user clicks outside the menu. Oddly, the button only seems to work once before completely losing fun ...

What are some tips for integrating Bluebird into Angular frameworks?

I attempted to integrate Angular with Bluebird promises: Here is the HTML code snippet: <body ng-app="HelloApp"> <div ng-controller="HomeController">{{name}} {{also}}</div> </body> The corresponding JavaScr ...

Session-based Authorization

I'm completely new to working with express.js, and I've been facing an issue while trying to create a session-cookie after logging in. Even though I can initiate the session and successfully log in, the session data doesn't carry over to the ...

Sending arguments to child components within KnockoutPassing parameters to child components in

My coding setup includes the following template: <template id="item-list"> <form action="" data-bind="submit: addItem"> <input type="text" name="addItem" data-bind="value: newItem"> <button type="submit">Add Item</butt ...

strange occurrences in localToWorld transformation

Hello there! Currently, I'm working on a project where I'm generating a TextMesh using font geometry and placing it within an empty pivot object. My goal is to obtain the world coordinates of each vertex in the TextMesh so that I can manipulate ...

Guide to developing JavaScript code that moves information from one local website to a different one

Here's the scenario: You input text into a field on website A and click a button. Upon clicking that button, the entered text should appear in website B. I attempted to use localStorage for this functionality, but unfortunately it was not successful. ...

The display of temporary headers - Nodemailer - AJAX

I keep receiving a warning in the request header that says: Provisional headers are shown. I'm struggling to identify the root cause of this issue. This warning prevents the readyState from changing and my callbacks on the eventhandler onreadystatecha ...

Begin counting when a particular div element is visible on the screen

I have a plugins.init.js file that contains a try-catch block which runs on page load. I am looking for a way to execute this code only once when the div with the class counter-value comes into view. Is there a method to achieve this? try { const count ...

Tips for concealing content within table cells

I am facing an issue with my form that contains a table. When the user clicks on the radio button labeled "No", I want the content of the subsequent cells in that row to become visible. However, when they click on "Yes", the content should be hidden again. ...

A method to deactivate a button cell after it has been clicked within a for loop

I am struggling with correctly disabling a button in my React code when it is clicked. I attempted to pass in an array and handle the button click, but it consistently results in errors. This task seems more complicated than it should be. How can I ensure ...