Home > Mobile >  fetch in for nodejs
fetch in for nodejs

Time:11-18

I run this code I want to send the request immediately but after all the for loop is executed. I want to do other things in the loop and not wait for answers. I will react to the answers whenever they come

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

response is here: all sequence number generate. fetch run after that.

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

i want this result for example:

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

CodePudding user response:

I just created a small sample snippet. What you basically need to do is to "wait" for each call to be fulfilled before going to the next call.

Be aware that you might getting a better performance to call the external API multiple times so you don't need to wait on each request to be fulfilled after each other.

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);
  }
})()
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related