Photo by Becca Tapert on Unsplash

As part of providing some API usage examples, I worked up an example that includes how to page through an Api using async/await. I won’t go to much into detail here since the pattern speaks for itself.

The code could be condensed and improved, but I left it verbose for clarity and its not really the point. For example, instead of doing:

let response = await reqUsers(token, offset)

records.push.apply(records, response)

We could refactor to this:

records.push.apply(records, await reqUsers(token, offset))

Without the use of Async/Await you would need a much clunkier pattern or recursion. Otherwise you would call the API endlessly in an concurrent manner.

Further notes can be found at the bottom of the article.

Notes:

The example code includes a request to get an oAuth token. It’s not really part of the meat of the example, but I decided to keep it in case someone found it useful.

The Go function kicks off the program and populates the users array hoisted at the top. If this doesn’t work for you, you can add a simple return statement to the bottom of the function and encapsulate the users array within the function.

const go = async () => { let users = [] // .... clipped for brevity

// we're all done. return the users array. return users;

}

No error handling is included. In a real application, you would want to catch error with a try/catch block.