【问题标题】:fetch in for nodejs获取nodejs
【发布时间】:2021-12-28 07:35:08
【问题描述】:

我运行这段代码我想立即发送请求,但在所有 for 循环执行之后。我想在循环中做其他事情,而不是等待答案。每当答案出现时,我都会做出反应

var fetchUrl = require("fetch").fetchUrl;
for (var i = 0; i < 10; i++) {
  console.log(i);
  checkbalance(i);
}

function checkbalance(req) {
  var urlCheckBalance =
    "https://api.etherscan.io/api?module=account&action=balancemulti&address=" +
    req +
    "&tag=latest&apikey=<api key>";

  // source file is iso-8859-15 but it is converted to utf-8 automatically
  fetchUrl(urlCheckBalance, function (error, meta, body) {
    console.log(body.toString());
  });
}

响应在这里:所有序列号生成。 fetch 之后运行。

0
1
2
3
4
5
6
7
8
9
{"status":"0","message":"NOTOK","result":"Error! Invalid address format"}
{"status":"0","message":"NOTOK","result":"Error! Invalid address format"}
{"status":"0","message":"NOTOK","result":"Error! Invalid address format"}
{"status":"0","message":"NOTOK","result":"Max rate limit reached"}
{"status":"0","message":"NOTOK","result":"Max rate limit reached"}

我想要这个结果,例如:

    0
    1
{"status":"0","message":"NOTOK","result":"Error! Invalid address format"}
    2
    3
    4
    5
    6
    7
 {"status":"0","message":"NOTOK","result":"Error! Invalid address format"}
    8
    9
     
    {"status":"0","message":"NOTOK","result":"Error! Invalid address format"}
    {"status":"0","message":"NOTOK","result":"Max rate limit reached"}
    {"status":"0","message":"NOTOK","result":"Max rate limit reached"}

【问题讨论】:

  • 你的环境支持 ES6 吗?
  • 如果我使用它,它会起作用吗?以及如何?

标签: node.js http request fetch


【解决方案1】:

我刚刚创建了一个小样本 sn-p。 您基本上需要做的是“等待”每个呼叫完成,然后再进行下一个呼叫。

请注意,多次调用外部 API 可能会获得更好的性能,因此您无需等待每个请求一个接一个地完成。

async function checkbalance(i){
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      console.log('resolved', i)
      resolve();
    }, 100);
  })
}

(async() => {
  for (let i = 0; i < 10; i++) {
    console.log(i);
    await checkbalance(i);
  }
})()

【讨论】:

    猜你喜欢
    • 2016-11-17
    • 2018-06-17
    • 2018-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-06
    • 2013-04-10
    • 2019-03-12
    相关资源
    最近更新 更多