[英]Javascript axios post after a while loop async / promise
我是 async/await 的新手,我需要一点帮助。 我想要实现的是在 while 循环完成后发送和 axios 发布请求。
如何将 while 循环放入异步 function 并等待它?
这是当前代码:
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})...
我想也许是这样的,但这个不起作用:
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})...
有什么建议可以告诉我正确的方向吗? :) 非常感谢
如果你打算使用 async/await,你不应该使用then
。 使用await
而不是then
。 下面的例子应该是你需要的。
showResults: async 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('');
const response = await fetch('https://' + randomChars + '.ipleak.net/json/?query_type=mydns');
const data = await response.json();
vm.dnsResult.push(data);
start++;
}
axios.post(apiUrl, {lat: vm.geoLat, lon: vm.geoLon, dns: vm.dnsResult})...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.