Performing a JavaScript Axios POST request following a series of iterations using a while loop with

Just getting started with async/await and feeling a bit lost. I'm trying to figure out how to send an axios post request after a while loop finishes.

Is there a way to wrap the while loop in an async function and await for it?

Here's the code snippet I'm working with:

showResults: function () {
            let vm = this;


            let apiUrl = '/api/test';
            let randomCallCount = Math.floor(Math.random() * (80 - 50 + 1) + 50);
            let start = 1;

            while (start <= randomCallCount) {
                let randomChars = [...Array(40)].map(i => (~~(Math.random() * 36)).toString(36)).join('');
                fetch('https://' + randomChars + '.ipleak.net/json/?query_type=mydns')
                        .then((resp) => resp.json())
                        .then(function (data) {
                            vm.dnsResult.push(data);
                        });

                start++;
            }

            axios.post(apiUrl, {lat: vm.geoLat, lon: vm.geoLon, dns: vm.dnsResult})...

I tried modifying it like this, but it doesn't seem to be working as expected:

fetchDNSData: async function () {
            let vm = this;
            let promise = new Promise((resolve, reject) => {
                let randomCallCount = Math.floor(Math.random() * (80 - 50 + 1) + 50);
                let start = 1;

                while (start <= randomCallCount) {
                    let randomChars = [...Array(40)].map(i => (~~(Math.random() * 36)).toString(36)).join('');
                    fetch('https://' + randomChars + '.ipleak.net/json/?query_type=mydns')
                            .then((resp) => resp.json())
                            .then(function (data) {
                                vm.dnsResult.push(data);
                            });

                    start++;
                }
            });

            let result = await promise; // wait until the promise resolves (*)

            return result;
        },

        showResults: function () {
            let vm = this;


            let apiUrl = '/api/test';

            vm.fetchDNSData().then(
                    response => {
                        axios.post(apiUrl, {lat: vm.geoLat, lon: vm.geoLon, dns: vm.dnsResult})...

Any guidance on where I might be going wrong? Your help is much appreciated! 😊

Answer â„–1

When implementing async/await in your code, it is recommended to avoid using then and instead use await. The following example illustrates this concept.

displayResults: async function () {
            let view = this;

            let apiUrl = '/api/example';
            let randomRequestCount = Math.floor(Math.random() * (80 - 50 + 1) + 50);
            let start = 1;

            while (start <= randomRequestCount) {
                let randomCharacters = [...Array(40)].map(i => (~~(Math.random() * 36)).toString(36)).join('');
                const response = await fetch('https://' + randomCharacters + '.example.com/json/?query_type=mydns');
                const information = await response.json();
                view.dnsResults.push(information);

                start++;
            }

            axios.post(apiUrl, {latitude: view.geoLat, longitude: view.geoLon, dnsData: view.dnsResults})...

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

The jQuery prop("disabled") function is not operating as expected

Although I've seen this question answered multiple times, none of the suggested solutions seem to be working for my specific example. Hopefully, a fresh set of eyes can help me figure out what's going wrong. Even after adding alerts to confirm t ...

Exploring the functionality of placeholders within jQuery

I am trying to create a customizable text template where I can insert placeholders and then fill those placeholders with data to use on my page. For example: var template = '<div class="persons">'; template += '<p> <span clas ...

Hello, I'm looking for assistance with this ReactJS code. Is there anyone who can help me

I am not receiving any output and also not encountering any errors, how can I resolve this issue? import React from 'react' function Array() { function myConcat() { const Villain = ["Harley Quinn", "Brainiac", "Deathstroke"]; cons ...

Using Axios: Manually Adding the X-XSRF-TOKEN Header

Currently, I am in the process of building a server-side rendered application with Vue. The API backend is created using Laravel framework and for sending requests to the API, I am utilizing axios. My current challenge involves making a POST request on th ...

Integrate new functionality into the plugin's JavaScript code without directly editing the JS file

I need to incorporate a new function called 'setInputDataId' at the same level as the existing function '_select' in the plugin js file without directly modifying the file itself. I am seeking guidance on how to add this new function. ...

`Proliferating values through constantly changing addition`

I am facing an issue with my code that involves 3 input fields: <div class="row"> <input onblur="calc_basic_amount();" id="rate_basic"></input> <input onblur="calc_basic_amount();" id="qty_b ...

Mastering NodeJS Promises: Efficiently Handling Multiple http.get Requests

I have recently started learning about NodeJS and Promise functionality, so please be patient with me if this question seems uninformed. My goal is to first retrieve a database of records and then verify that the links associated with these records return ...

Tips for managing nested objects within React state and keeping them updated

Could someone kindly point out where I might be going wrong with this code? Upon checking the console.log, it seems like the date function is functioning correctly. However, despite using this.setState, the timestamp remains unchanged. Any help would be gr ...

Is it possible to eliminate the arrows from an input type while restricting the change to a specific component?

Is there a way to remove the arrows from my input field while still applying it only to the text fields within this component? <v-text-field class="inputPrice" type="number" v-model="$data._value" @change="send ...

The click event is not being triggered by Testing-Library React following an asynchronous operation

Currently, I am in the process of creating a Jest test. It appears that when fireEvent.click is called after an asynchronous it, the function does not get triggered. In this scenario, it is evident that a few lines of code speak louder than lengthy explan ...

Employing a for loop to verify the existence of a JSON key

Currently, I am attempting to loop through an EJS JSON object and verify the existence of values. If a value does exist, I want to add the corresponding URL to an array further down. Upon loading the page, I am encountering an issue where I am informed th ...

various issues with fonts and Uncaught Eval error

I've been encountering multiple font/style errors and an uncaught eval. I have attached a picture for reference. My Angular application is not functioning properly, and I suspect these errors may be the reason. However, I am unsure of their significan ...

Encountering a data retrieval issue when using the useSWR hook in a project using reactjs

I am trying to retrieve data from the backend using useSWR. However, I have encountered two bugs in the function getDataUseSWR. The errors occur at line 'fetch(url).then': 1: "Expected 0 arguments, but got 1."; 2: "Property 'then' does ...

Utilizing Angular: Filtering Views Based on JSON Data Values

I am struggling to figure out why a basic Angular filter is not working for me in this example. Despite following the recommended format I found online, it does not seem to be functioning properly. Essentially, I just need to display information from the a ...

Exploring the world of unit testing in a store - any tips on getting it to work

I am currently working on a store.js file import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) export const mutations = { increment: state => state.count++, Changeloading(state, status) { state.loading = status }, Cha ...

What is the reason for the omission of H1 tags from the table of contents list in NuxtJS's Content module?

Currently, I am facing an issue with importing a large amount of markdown content that heavily utilizes H1 (#) tags. While trying to create a table of contents (TOC) component, I noticed that the @Nuxt/Content package does not include H1 tags in the provid ...

tips for personalizing your jQuery image preview script

Currently, I have implemented a jQuery script that allows me to preview multiple images before uploading them. Although the functionality works well, I am facing difficulties customizing it to meet my specific requirements. <script> $(document).r ...

Tips on utilizing controllers within AngularJs directives?

In order to utilize a controller in my directive, what is the best way to access all controller functions within the directive? directive.js angular.module('App').directive('deleteButtons', function (prcDeleteFactory,$rootScope) { & ...

What is the easiest way to include a copyright symbol in a React component?

I am trying to include the copyright symbol in a React component, but it doesn't seem to be working for me. function Footer() { return ( <footer> <p>&copy</p> </footer> ); } <p>&copy</p> ...

Using the Facebook marketing API requires a valid Instagram account ID to be provided as a parameter

I've been exploring the capabilities of the Facebook Marketing API once again. After successfully creating Facebook ads using my Node.js app, I now have my sights set on Instagram. My current call to create an AdCreative looks like this: fb.api(&ap ...