Hey there! You're using an out-of-date browser, so this site probably looks pretty funny. Upgrade your browser for the full experience.
dev header

Recursive asynchronous calls with JavaScript and ES6

ES6 generator functions make recursive asynchronous calls (relatively) easy.

To avoid sending too much data all at once, many APIs return paginated results. Most of the time (especially when you’re displaying the results), that’s exactly what you want.

Sometimes, though, you want to collect all of that data first, then do stuff with it. While this is technically possible with basic JS and Promises, it gets ugly fast!

Here’s where ES6 generator functions can simplify things.

Let’s pretend we’re calling an API that returns a payload like this:

(If you don’t want to pretend, take a look at the Mailgun Events API since that’s what this exercise is based on.)

Step 1: Define a generator function which calls the API

This function runs in an infinite loop and will return the results of the last ajax call each time generator.next() is called. The function also changes the url it’s calling so that it’s getting the next page of data on each call.

Step 2: Define a function to call our generator.

This function initializes our generator, then calls itself recursively, getting each page of data back from the generator until there is no more data.

Step 3: Start the process by calling our function

This is still a little tricky to conceptualize (as recursion always is), but it’s a powerful way to tackle this problem with a minimal amount of code.

Born and raised in
Louisville, Kentucky.


223 S. Clay St

Work With Us

  • This field is for validation purposes and should be left unchanged.