获取 nodejs

fetch in for nodejs

我运行这段代码我想立即发送请求但是在执行完所有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());
  });
}

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

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

我刚刚创建了一个小样本片段。 您基本上需要做的是在进行下一个调用之前“等待”每个调用完成。

请注意,多次调用外部 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);
  }
})()