I am trying to collect data asynchronously using jQuery and Promise. Here's a brief idea of my code:
(function () {
let promises = [], results = [];
const urls = ["https://cdn.jsdelivr.net/gh/rails/rails/MIT-LICENSE"];
for (let url of urls) {
let p = $.get(url).then(
// The actual job is to parse the response and make new requests
// but for simplicity I'll just make the same request again here
() => promises.push(
$.get(url).then(
data => results.push(data))));
promises.push(p);
}
console.log("Start");
Promise.all(promises).then(function () {
console.log("Done");
console.log(results);
});
})();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
The strange thing is, I can see a noticeable delay before the console.log
runs, but an empty array appears in my console. However, if I immediately enter results
, I can see everything expected there. I see no error, either.
I believe it has something to do with me nesting promises in promises, but I have no idea how to hunt the bug down.