javascript - 你如何让axios GET请求等待?

标签 javascript node.js arrays axios fetch-api

您好,我在将 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/

相关文章:

javascript - 是否可以在 HTML 标记中插入您的属性?

javascript - Node.js:如何测试函数

javascript - 文本/纯文件下载的 Angular http$ 响应失败,出现 SyntaxError : Unexpected number in JSON

javascript - 在node.js中,控制台显示成功日志,但是localhost : 3000 is not connected

php - 使用两个不同的 foreach 循环 PHP/SQL 添加到同一个数组

javascript - 我怎样才能让 <img> 元素重新评估它的 onerror?

javascript - 迁移到 TypeScript 后 Jest 测试无法正常工作

arrays - 从数组中删除行

arrays - 为什么 Go 的 strings.Fields(str) 和 strings.Split(str, "") 这么慢?

javascript - Javascript 中的 XOR 运算符用于检查值