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! 😊