【问题标题】:How do you make axios GET request wait?你如何让 axios GET 请求等待?
【发布时间】:2019-07-08 02:48:28
【问题描述】:

您好,我在使用 axios / fetch GET 时遇到问题,该 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

c、b、a

等等

但我希望它按照顺序输出所以应该是

a ,b ,c 总是

【问题讨论】:

  • 试试 rxjs forkjoin 函数
  • 它遵循顺序,但并非所有请求都同时完成——这就是异步操作的基本思想。每当他们完成时,他们就完成了。如果您需要等待所有结果,请使用Promise.all
  • @AlbertiBuonarroti 把它变成答案
  • 另请注意,JS 实现并不总是按输入顺序返回数组。

标签: javascript arrays node.js axios fetch


【解决方案1】:

选项 1:Promise.all

简而言之:如果您需要特定订单,可以使用Promise.all()。您创建一个充满承诺的数组,将其传递给Promise.all(),您将获得一个包含已解决承诺的数组。

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));

但是,由于第一个拒绝的承诺的原因,它失败了。因此,如果您有一个大数组或需要显示任何数据,则不应使用此方法。此外,这将只保留客户端上的订单!您的后端不会知道任何关于订单的信息,因为调用没有按顺序完成。

选项 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 得到解决。

【讨论】:

    【解决方案2】:

    使用 Promise.all ,以保持顺序。

    在 for 循环中,我创建了三个 fetch Promise 并链接然后以 json 格式获取响应并将它们推送到数组。

    最后,我使用 Promise.all 来获取预定义格式的数据

    const fetch = require("node-fetch");
    
    algo = "eth" // algorithm for wtt
    
    hashrate = ['250', '100', '50']
    
    console.log(hashrate)
    
    var fetchUrl =[]
    for (var i = 0; i < vhr.length; i++){
    
    return fetchUrl.push(fetch("https://whattomine.com/coins.json?" + algo + "=true" + "&factor%5B" + algo + "_hr%5D=" + hashrate[i]).then(response => response.json())
    }
    
    
    Promise.all(fetchUrl)
    .then(function(data) {
      data.forEach(a => a.coins.Ethereum.btc_revenue)
      })

    【讨论】:

      【解决方案3】:

      您可以通过以下方式使用递归:

      function fetchRecursively(int currentStep, int n) {
          var wttURL = "https://whattomine.com/coins.json?" + algo + "=true" + "&factor%5B" + algo + "_hr%5D=" + hashrate[currentStep]
          fetch(wttURL)
              .then((resp) => resp.json()) // Transform the data into json
              .then(function(data) {
                  console.log(data.coins.Ethereum.btc_revenue);
                  if (currentStep < n) {
                      fetchRecursively(currentStep + 1, n);
                  }
              })
      }
      

      并替换for循环:

      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)
        })
      

      用这个:

      fetchRecursively(0, vhr.length);
      

      【讨论】:

      • 如果您的环境不支持,可以模拟await 的好主意!
      猜你喜欢
      • 1970-01-01
      • 2022-10-01
      • 2020-06-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-18
      • 1970-01-01
      • 2020-02-14
      相关资源
      最近更新 更多