Home > database >  Can't use async/await with Axios and array.map() with settimeout inside it
Can't use async/await with Axios and array.map() with settimeout inside it

Time:08-18

I am using an API that only allows 3 calls per second, and I need to make a lot of calls.

So i need to use SetTimeout with Await Axios inside a map, but i am not being able to achieve it.

I tried import setTimeout from promises, but no luck.

import { setTimeout } from 'timers/promises';

const apiCall = await Promise.all(data?.map( async item => {
  
  await setTimeout(resolve, 334)
  

  const numeroPedidoBling = item?.numeroPedidoBling;
  
  
  const orderData = await axios.get(`${BLING_URL}/${numeroPedidoBling}/json?apikey=${APIKEY}`, { headers: {
    'Accept': "application/json"
  }})


  return orderData?.data?.retorno;
}))

I tried in a lot of different ways, and now i am stuck in this piece of code.

Right now, it does not wait for the api calls and I receive erro 429 (too many calls)

How can I make it?

Obs.: 334 inside SetTimeout is 1,01 second

Edit.: I tried implementing rateLimit and for await together, but it also gives error 429, too many requests, follow the code:

try {

const result = [];

for await (let item of data) {
  const numeroPedidoBling = item?.numeroPedidoBling;

  const request = rateLimit(axios.create(), { maxRPS: 2 })
  
  
  const orderData = await request.get(`${BLING_URL}/${numeroPedidoBling}/json?apikey=${APIKEY}`, { headers: {
    'Accept': "application/json"
  }})

  result.push(orderData?.data?.retorno);
}

} catch (error) {
throw Error(error)

}

CodePudding user response:

I managed to make it by using for await, and setTimeout, as I was needind to make only 3 api calls per second, it worked.

follow the code:

import { setTimeout } from 'timers/promises';
import axios from 'axios';

const result = [];
let counter = 0;

for await (let item of data) {
  counter =1

  const numeroPedidoBling = item?.numeroPedidoBling;

  if(counter%3 === 0) {
    await setTimeout(1000)
  }
  
  
  const orderData = await axios.get(`${BLING_URL}/${numeroPedidoBling}/json?apikey=${APIKEY}`, { headers: {
    'Accept': "application/json"
  }})

  result.push(orderData?.data?.retorno);
}

CodePudding user response:

User concept debouncing-throttling

https://medium.com/nerd-for-tech/debouncing-throttling-in-javascript-d36ace200cea#:~:text=Summary:,irrespective of continuous user actions.

  • Related