Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses and challenges
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Calculator

0

53
Views
Using _.throttle on a function that needs to take different input values

I am coding in Node.js and would like to use lodash's throttle method on an array of axios requests. I have a process, being run in an AWS lambda function, that receives as input an array of parameters. Each of these parameters is used to configure an axios request to an external API and do something with the data in the response. Thus, for example, if we get 1000 parameters in this array, 1000 calls will need to be made to this external API.

In my example, makeCallToApi is an imported class defined elsewhere, containing a static async function execute(param) which constructs a request config for axios using the input param (used in constructing the url) and then tries to return the response of await axios(config).

await Promise.all(
  arrayOfParams.map(async (param) => {
    const data = await makeCallToApi.execute(param);
    await myMongooseModel.create(formatData(data));
  })
);

The external API is rate-limited, so I want to throttle these requests to avoid hitting their limit. How would I use _.throttle to do this? I have the following example below, which I know is wrong and would like to understand how to rewrite correctly:

// in the file where makeCallToApi is defined:
const throttledCallToApi = _.throttle(axios); 

export class makeCallToApi {
   static async execute(param) {
      const config = ... // construct the request config; url = `${baseUrl}/example-api/${param}`
      try {
       const response = await throttledAxios(config);
       return response?.data;
       } catch (err) {
          // error-handling stuff
      }
  }
}

// then, in my main code...

await Promise.all(
  arrayOfParams.map(async (param) => {
    const data = throttledCallToApi(param);
    await myMongooseModel.create(formatData(data));
  })
);

The problem with this is that although I am looping over the entries in arrayOfParams, throttledCallToApi() keeps being called with the value of the first param in the arrayOfParams. What am I doing incorrectly in the usage of _.throttle()?

7 months ago ยท Juan Pablo Isaza
Answer question
Find remote jobs