您好,我在将 axios/fetch GET 与 URL 结合使用时遇到问题,该 URL 的参数会遍历数组循环获取其值
axios/fetch 不遵循数组的顺序,只返回最先出现的响应。
我该如何解决这个问题?
const fetch = require("node-fetch");
algo = "eth" // algorithm for wtt
hashrate = ['250', '100', '50']
console.log(hashrate)
for (var i = 0; i < vhr.length; i++){
var wttURL = "https://whattomine.com/coins.json?" + algo + "=true" + "&factor%5B" + algo + "_hr%5D=" + hashrate[i]
fetch(wttURL)
.then((resp) => resp.json()) // Transform the data into json
.then(function(data) {
console.log(data.coins.Ethereum.btc_revenue)
})
当前的输出是 250 (a)、100 (b) 或 50 (c) 的结果
所以基本上它要么出来
a, b, c(期望的)
b, c, a
a, c, b
三、二、一
等等
但是我想让它按照顺序输出所以应该是
总是a,b,c
最佳答案
选项 1:Promise.all
简而言之:您可以使用 Promise.all()如果您需要特定订单。您创建一个充满 promise 的数组,将其传递给 Promise.all()
,您将获得一个包含已解决 promise 的数组。
const fetch = require("node-fetch");
algo = "eth" // algorithm for wtt
hashrate = ['250', '100', '50']
wttURL = [];
for (var i = 0; i < vhr.length; i++) {
wttURL.push(fetch("https://whattomine.com/coins.json?" + algo + "=true" + "&factor%5B" + algo + "_hr%5D=" + hashrate[i]))
}
Promise.all(wttURL)
.then(responses => responses.forEach(response => console.log(response)))
.catch(err => console.log(err));
但是,它失败了,原因是第一个拒绝的 promise 。所以如果你有一个大数组或者你需要显示任何数据你不应该使用这个方法。此外,这只会在客户端保留顺序!由于调用未按顺序完成,因此您的后端将不知道有关顺序的任何信息。
选项 2:异步/等待
您可以改用 async/await
。您将 await
每个结果,如果其中任何一个失败您都不在乎,因为其余的仍然可以成功。此外,您的后端也可以跟踪订单。
async function getData() {
for (var i = 0; i < vhr.length; i++) {
let wttURL = "https://whattomine.com/coins.json?" + algo + "=true" + "&factor%5B" + algo + "_hr%5D=" + hashrate[i]
await fetch(wttURL)
.then(resp => resp.json()) // Transform the data into json
.then(data => console.log(data.coins.Ethereum.btc_revenue))
.catch(err => console.log(err));
}
}
这种方法保留了客户端和后端的原始顺序(如果您记录它)。但是,它比第一个解决方案慢,因为它不会继续下一个 fetch
,直到 promise 得到解决。
关于javascript - 你如何让axios GET请求等待?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54684255/