-2

I have an array of endpoints I'd like to query like so: const apiList = ['/api1', '/callme', '/thisonetoo']

Using axios, a promise based library, I can dynamically generate a promise by mapping the array ->

Promise.all(apiList.map(name => promiseGet(name))).then(res => ...)

This works fine... but it calls the server too fast, and some of the apis get denied, which causes the entire program to mess up.

Is there a way to throttle / debounce and wait 500ms before creating or calling the next endpoint?

Limiting the amount of Promises open isn't enough it seems. I have to perform some sort of "sleep" operation and wait a little bit before calling the next api endpoint in the array.

eddiewang
  • 415
  • 5
  • 21
  • 2
    Have you looked at [similar Promise throttling questions](http://stackoverflow.com/q/38385419/1426891)? There are [a lot of general Promise throttling requests](http://stackoverflow.com/search?q=%5Bpromise%5D+throttle), which might help narrow the focus of the question if it's not covered in those. – Jeff Bowman May 16 '17 at 18:59
  • 1
    Possible duplicate of [Throttle amount of promises open at a given time](http://stackoverflow.com/questions/38385419/throttle-amount-of-promises-open-at-a-given-time) – Jeff Bowman May 16 '17 at 19:02
  • Possible duplicate of [ES6 Promise replacement of async.eachLimit / async.mapLimit](http://stackoverflow.com/questions/43892296/es6-promise-replacement-of-async-eachlimit-async-maplimit) – jib May 17 '17 at 01:39

2 Answers2

-2

maybe call them serially?

const apiList = ['/api1', '/callme', '/thisonetoo'];

function doNext() {
  const uri = apiList.shift();
  axios.get(uri)
    .then(doNext);
}

You can add a setTimeout within doNext if you want additional throttling.

Ivo
  • 535
  • 2
  • 13
  • that seems to make alot of sense, but it doesn't seem like the data resolves at the end to one array? – eddiewang May 16 '17 at 19:05
  • It was just an example, no error or additional handling. You will need to expand the `then` handler to collect the responses. Also verify `shift` should only be called on `length > 0` – Ivo May 16 '17 at 19:08
-2

I would recommend adding a concurrency parameter to the call:

Promise.all(apiList.map(name => promiseGet(name), { concurrency: 10 })).then(res => ...).

You can also use Promise.delay(500) to have the method calls wait before executing

  • thanks. is this avl in the core api or just third party promise libs like Bluebird? and could you show an example of how one could use the delay? appreciate it! – eddiewang May 16 '17 at 19:15