I am using an asynchronous JavaScript http client to download & process some paged JSON data from an initial URI & subsequent page URIs.
Each JSON page includes the URI for the next page, if there are more pages.
Sometimes, I need to process all pages for an initial URI & its subsequent page URIs before progressing to the next completely new initial URI.
I'd prefer to use await calls to the async http client to handle the initial URI & all subsequent page URIs all within an single call to my own async function (named f()), calling .then() on the Promise returned from f() to process a second initial URI only after the first initial URI & all of its pages have been downloaded & processed, rather than having to pass a callback to f() that I must manually call at the end of f().
e.g., can f() and/or the code that uses it below be modified such that 'uri2' will only be processed after all pages of 'uri1' have been processed without resorting to something like the manual callback mechanism in g()?
async function f(initialPageUri) {
let nextPageUri = initialPageUri
while (nextPageUri) {
const o = await getObjectFromJsonFromUri(nextPageUri)
// do stuff with o
nextPageUri = o.nextPageUri
}
}
f('uri1').then(() => f('uri2'))
async function g(initialPageUri, then) {
let nextPageUri = initialPageUri
while (nextPageUri) {
const o = await getObjectFromJsonFromUri(nextPageUri)
// do stuff with o
nextPageUri = o.nextPageUri
}
then()
}
g('uri1', () => g('uri2', () => {}))
Simplified logging from my real code: <url letter> <page number or _ if no more pages> in order of requesting:
A 1
A _
B 1
C 1
D 1
E 1
F 1
E _
D _
B 2
C _
F 2
B 3
F _
B _
Your first solution should work as-is.
Any
asyncfunction returns a Promise by default. You can do.thenon the result of theasyncfunction as you do in your first block of code withf.Additionally, you can perform
awaitonasyncfunctions to wait for thePromiseto resolve before continuing. That is exactly what you do in your call togetObjectFromJsonFromUri.Quick demo: