Push to global array from multiple API requests
<p>I have a function that calls a paginated API. It makes an initial call to the first page, then continues to make requests to the subsequent pages using the <code>next</code> url returned in the response. It does this until <code>next</code> is <code>null</code>. I am trying to extract data (city names) from the response and push these to a global array.</p>

<p>My code currently looks like this:</p>

<pre><code>var results = [];
function nextPage(url) {
    if (!url) {
        return;
    }
    $.getJSON(url, function(data) {
        nextPage(data.next);
        $.each(data.results, function (k, v) {
            results.push(v.city_name);
        });
    });
}

nextPage('http://url.com/api/v1/cities/?page=1');
console.log(results);
</code></pre>

<p>Assuming I have two pages of JSON that look like this:</p>

<p><em>Page 1</em></p>

<pre><code>{
    "count": 105,
    "next": "http://url.com/api/v1/cities/?page=2",
    "previous": null,
    "results": [
        {
            "city_name": "Paris"
        },
        {
            "city_name": "Brussels"
        }
    ]
}
</code></pre>

<p><em>Page 2</em></p>

<pre><code>{
    "count": 105,
    "next": null,
    "previous": "http://url.com/api/v1/cities/?page=1",
    "results": [
        {
            "city_name": "Manchester"
        },
        {
            "city_name": "Curitiba"
        }
    ]
}
</code></pre>

<p>I would expect the array to look like this:</p>

<pre><code>["Paris", "Brussels", "Manchester", "Curitiba"]
</code></pre>

<p>However, when I log <code>results</code> to the console the array is empty. Can anyone help? Let me know if you need any more information. Cheers</p>