Our WorkAbout UsOur ApproachThe Journal
Contact »
« Back to the journal
PHP, Javascript & React

Recursive asynchronous calls with JavaScript and ES6


Mark Biek
Mark Biek

on 1/30/2018

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.

Share to

Related Posts

What's the JAMstack?

By:Alec Robertson

As a front-end developer in 2020, it is time that I fulfill the FEDeral mandate that I publish words regarding the JAMStack. If you follow too many developers on Twitter, it’s likely you’ve heard about the Next Big Thing in web development, but I’d like to put this trend (fad? movement?) into context to better understand what’s truly new about this approach and whether it’s worth using.

Read More »
Debugging a ReactJS Chrome Extension

By:Mark Biek on 3/5/2018

Simplify debugging your React-based Chrome Extension using the handy remote-redux-devtools library.

Read More »