In this lesson, the planner looked up Mateo’s country code by its name, Mexico, in the World Bank’s list of countries, a list that comes back one page at a time. You followed it from page to page until it ran out, with a limit on how many pages the loop may ask for.
Key Points
- You know Mateo meant MX, but the planner can’t guess that from XX. Every friend knows their country’s name, though, and Mateo’s is Mexico. The World Bank lists every country with its code, so the planner can look the code up by name.
- A first try asks for the whole list,
https://api.worldbank.org/v2/country?format=json. The first element of the body holds the paging fields. They say this is page one of six, and the list has 296 entries in all. The second element holds only 50 of them. Mexico isn’t among those 50, so.find()givesundefined. - Watch out: a list endpoint can answer with its first page only. Nothing fails, and only the paging fields say the rest is missing. The 296 also include regions and income groups, such as Africa Eastern and Southern.
getAllCountries()asks again, once per page. Its loop counts pages from one, as the World Bank does, and never pastmaxPages, ten by default. Each pass builds the URL with that page number and a page size of 50. Many APIs cap that size, so bigger pages can’t replace the loop. It leaves out the last lesson’s shape check, to stay short.- Each pass checks
response.ok, splits the body into the paging info and the entries, and adds the entries to the end of one list. - The stop condition reads the paging fields: when the page that came back reaches the number of pages, nothing’s left to ask for, so the function returns the list.
- With six pages, the loop sends six requests, page one included, because it starts over at page one. It returns at page six, long before ten. Mexico comes by on page four, but the loop keeps going, because the script looks for Mexico only once it has the whole list. Then
.find()looks up the name Mexico. It found an entry, so the check passes, andMXis the code it logs. The planner found MX from the name alone. - The loop’s second way to stop is
maxPages, a limit you choose, ten unless you pass a number. Without a limit, a server that never said it was on the last page would keep the loop asking forever. When the passes run out before the last page, the function’s promise rejects, with an error that says why, andcapped.mjscatches it. It doesn’t return part of the list, which could miss Mexico without any error, like the first try.
The rule to remember is that a list can come back one page at a time. Read its paging fields, and ask for each next page until the page number, page, reaches the number of pages, pages. Set a limit too, one that says so when it’s hit.