0

I am new to nodejs. I want to limit my external API call to 5 per minute. If I exceeds more than 5 API call per minute, I will get following error.

You have exceeded the maximum requests per minute.

This is my code. Here tickerSymbol array that is passed to scheduleTickerDetails function will be a large array with almost 100k elements in it.

public async scheduleTickerDetails(tickerSymbol: any) {
  for(let i=0;i<tickerSymbol.length;i++) {
      if(i%5 == 0){
      await this.setTimeOutForSymbolAPICall(60000);}
      await axios.get('https://api.polygon.io/v1/meta/symbols/' + tickerSymbol[i] + '/company?apiKey=' + process.env.POLYGON_API_KEY).then(async function (response: any) {
          console.log("Logo : " + response.data.logo + 'TICKER :' + tickerSymbol[i]);
          let logo = response.data.logo;
          if (await stockTickers.updateOne({ ticker: tickerSymbol[i] }, { $set: { "logo": logo } }))
              return true;
          else
              return false;
         })
        .catch(function (error: any) {
          console.log("Error from symbol service file : " + error + 'symbol:'+tickerSymbol[i]);
        });   
    }
}

 /**
  * Set time out for calling symbol API call 
  * @param minute 
  * @return Promise
  */
  public setTimeOutForSymbolAPICall(minute:any)  {
  return new Promise( resolve => {    
      setTimeout(()=> {resolve('')} ,minute );   
  })
   
}

I want to send 1st 5 APIs first, then after a minute I need to send next 5 APIs and so on. I have created a setTimeOut fucntion for this, but sometimes in my console

Error: Request failed with status code 429 : You've exceeded the maximum requests per minute.

James Z
  • 12,209
  • 10
  • 24
  • 44
Oops
  • 1,373
  • 3
  • 16
  • 46
  • ```i%2 == 0``` you are saying that every even ```i``` you call timeout? – cvekaso Oct 27 '20 at 11:06
  • I edited it to i%5, what I was looking for is send 5 apis per minute. So after 5 calls I need to pause the execution by calling timeout. – Oops Oct 27 '20 at 11:45
  • you should read Akash refers to the article - current problem is that you are not awaiting your Axios in for loop - and this return false/true doesn't have sense – cvekaso Oct 27 '20 at 11:48

1 Answers1

0

The for loop in JS runs immediately to completion while all your asynchronous operations are started.

Refer this answer.

Akash Dathan
  • 4,348
  • 2
  • 24
  • 45