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

Challenges with Websocket connectivity following AKS upgrade to version 1.25/1.26

We currently have a Vue.js application running on AKS with no issues on version 1.23, although some webpack/websocket errors are showing up in the console. However, after upgrading our AKS Cluster to either version 1.25 or 1.26, even though the pods are a ...

Learn how to implement a call to 'next()' in Express and Node.js only after successfully creating schemas

I am currently developing an event app, and within my 'Event' schema, I have an array of 'Tag' schemas, allowing each event to be associated with one or more tags. Event: var EventSchema = new Schema({ ... tags: [{ type: Schema.Type ...

Determining when a text area has selected text without constant checking

class MarkdownEditor extends React.Component { constructor(props) { super(props); this.timer = null; this.startIndex = null; this.endIndex = null; } componentDidMount() { this.timer = setInterval(() => { this.setSelectio ...

Capture a screenshot of the icons

I'm curious about displaying specific parts of images in a React Native application. class InstaClone extends Component { render() { return( <View style={{ flex:1, width:100 + "%", height:100 + "%" }}> <View style={st ...

Numerous criteria for selecting a checkbox

I am working with a student database table called student_db, which looks like this: Name Gender Grade City John Male 2 North Dave Male 4 North Garry Male 3 North Chirsty Female 5 East Monica Female 4 East Andrew Male ...

Tips for effectively combining the map and find functions in Typescript

I am attempting to generate an array of strings with a length greater than zero. let sampleArray2:string[] = ["hello","world","angular","typescript"]; let subArray:string[] = sampleArray2 .map(() => sampleArray2 .find(val => val.length & ...

After attempting to refresh the webpage with the F5 key, I noticed that the jQuery progress bar was not functioning properly. Additionally, the webpage failed to display any

Trying to implement a web loading bar using jQuery on my website was initially successful, but I encountered an issue when reloading the page with F5. The progress bar would not work and the webpage displayed only a white background. Below is the code snip ...

Manipulating viewport settings to simulate smaller screens on a desktop device

I am working with a parent container that contains Bootstrap div.row elements holding div.col-... child elements. I am using jQuery to adjust the width and height of the container dynamically to replicate mobile device sizes for users to preview different ...

ng-view is the culprit behind the website's fatal error

Encountering a "RangeError: Maximum call stack size exceeded" in the console while trying to recreate a basic routing example from w3schools. The crash seems to be linked to <div ng-view></div> in index.html. Despite making minimal changes from ...

What are the steps to run and test the renovate bot on your local machine

Before setting up renovate to work with my Azure pipeline, I wanted to test it locally using npx renovate to ensure everything is working as expected and that my config file is properly configured. I ran npx renovate --platform local command. My project i ...

Collecting Images Based on Quantity

Despite using async to download URIs on every request and closing when a certain count is reached, I am still encountering the issue of files not being downloaded properly and exiting before reaching their maximum. Can someone suggest the best solution t ...

How can a React app be developed offline?

I am currently working offline with no access to the internet. Node.js is already installed on my system, but I encountered an error when trying to run the command npm create-react-app. Is there a way for me to execute npm commands and set up a react app ...

Searching for different forms of multiple words using regular expressions

I have a value saved in a variable: var myvalue = "hello bye"; var myText = "hellobye is here and hello-bye here and hello.bye" Is there a way to check if different versions of myvalue are present in the text? I am currently using this pattern: hello ...

Is there a way to identify the moment when a dynamically added element has finished loading?

Edit: I've included Handlebar template loading in my code now. I've been attempting to identify when an element that has been dynamically added (from a handlebars template) finishes loading, but unfortunately, the event doesn't seem to trig ...

Invoking a function that is declared in a fetch request from an external source beyond the confines of the fetch itself

I am currently struggling with calling a function that is defined inside an API Fetch response function. My code sends an API fetch request to the GitHub API to retrieve a repository tree in JSON format. The problem arises when I try to call a function def ...

Check if the content key Json exists by implementing Vue

Can anyone help me with checking the existence of "novalue"? For instance: { name: "maria", city_id: "novalue" .... } What would be the best way to do this in Vue? Should I use <div v-if="condition"> or a function? ...

Exploring Autocomplete Functionality with SQLite Integration in Flask

I have been searching for a solution to my problem without any success. My SQLite database contains electronic products, and I have a search box that allows users to search for products by typing in their name. However, I want to enhance the user experienc ...

Implementing PHP echo alerts using Javascript

My current task involves validating the IP address entered in a textbox using PHP. $('#check_ip').click(function() { var iptext = $('#Ip_Txt').val(); $.ajax({ type : "POST", url : "mypage.php", data : { iptext : ip ...

It is important to ensure that the user returned by the onAuthStateChanged function in

server admin.auth().createCustomToken(uuid) .then((customToken) => { admin.auth().createUser({ email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ed989e889fad88958c809d8188c38e8280">[email protected] ...

JavaScript does not function properly on dynamically loaded content from AJAX requests and it is not relying on

I am currently using ajax to load all content from 'mysite/math/' into math.php. I want to render the loaded math content using katex. KaTeX GitHub Inside math.php, I include the Katex library from the CDN mentioned in the link above. The HTML ...