Search code examples
promiseaxiosbluebirdthrottlingrate-limiting

Rate limit/throttle for axios requests issue


In this class, the get(item) method returns a promise with the response data object that is obtained from the axios call

const wait = ms => new Promise(resolve => setTimeout(resolve, ms));

class MyClass {
    constructor () {}

    get(item){

      console.log(`making request`);
      return wait(250).then(
        axios.get(`https://some_url.com/${item.id}`, {
              params: { api_key: "some_key" }
          }).then((response) => {
              console.log(`RESPONSE IS ${response}`);
              return new Promise( (resolve) => { return resolve(response); })
          })
        )

    }
}
module.exports = MyClass;

this is the outer function that calls get(item) the axios wrapper method repeatedly.
It is using bluebirdjs' Promise.mapseries (http://bluebirdjs.com/docs/api/promise.mapseries.html)

var myClass = require('./myClass');
...
bluebird.mapSeries(someArray), function(arrayItem){
return new myClass().get(arrayItem)
 .then((response_object) => {
    //TypeError: Cannot read property 'then' of undefined
  });
})
.then(function(something){
  // do nothing
  })
});
...

the code fails in the higher level function where it throws TypeError: Cannot read property 'then' of undefined as it executes before the axios with 250ms delay is finished

This implementation is not working and I'm looking to fix it and rate limit/throttle correctly

Feedback appreciated


Solution

  • Change from this:

    return wait(250).then(axios.get(...))
    

    to this:

    return wait(250).then(() => axios.get(...))
    

    You have to pass a function reference to .then() so it can call it later. You were calling it immediately and passing its return result to .then() which is not how .then() works.

    Also, change this:

    return new Promise( (resolve) => { return resolve(response); })
    

    to

    return response;
    

    as they accomplish the same thing, but the second is a lot simpler.