0

I have an array which contains objects, which contains an array, which contains objects. It's a little messy, but this is just the way the Google Books API returns information.

var myList = [
        {kind:'book', totalItems:1, items: [{volumeInfo:{authors:['JRR Tolkien']},publishedDate:"1965",pageCount:355}]},
        {kind:'book', totalItems:1, items: [{volumeInfo:{authors:['HP Lovecraft']},publishedDate:"1930",pageCount:269}]},
        {kind:'book', totalItems:1, items: [{volumeInfo:{authors:['Oscar Wilde']},publishedDate:"1920",pageCount:400}]},
    ];
    
    console.log(myList);
    console.log(myList[1].items[0].pageCount);

I can access everything in here with no problems. When I create an identical array, except using an ajax call in jQuery, I can't access any of the objects or array items.

var bookList = $(".book").map(function () {
    return this.id;
  }).get();

  console.log(bookList);

  var thelink = "https://www.googleapis.com/books/v1/volumes?q=isbn:";
  var allresults = [];

  for (var i = 0; i < bookList.length; i++) {
    $.ajax({
      url: thelink + bookList[i],
      dataType: 'json',
      type: 'get',
      cache: true,
      success: function (data) {
        allresults.push(data);
      }
    });
  };
  
  console.log(allresults[1].items[0].pageCount);
<!doctype html>
<html>

<head>
    <title>Google Books</title>
    <meta charset="UTF-8">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    <link rel="stylesheet" type="text/css" href="style.css">
</head>

<body>
    <h1>Input</h1>
    <div id="book-container">
        <div id="0618249060" class="book"></div>
        <div id="9780743258074" class="book"></div>
        <div id="9780345466457" class="book"></div>
    </div>
    <h1>Result</h1>
    <div id="resultContainer">
        <!--Put a bunch of stuff here-->
    </div>
</body>

</html>

As I understand these should be accessible in the exact same way. My only clue is that in the console the variables 'myList' and 'allresults' show up slightly differently. The second one being accessible, the first not.

example

I'm very confused and have idea what to search to find a solution! What on earth am I doing wrong? Thank you!

Tom Parke
  • 119
  • 5
  • 1
    *"What on earth am I doing wrong?"* You are accessing the array before it was populated. This is evident by the fact that the first line renders `[]`, which means at the time you are actually calling `console.log`, the array is empty. – Felix Kling Mar 18 '19 at 23:22

2 Answers2

1

This is because ajax calls are asynchronous. So when for loop is finished, you have a console statement which is being executed but until that time, the ajax calls are not finished and hence you cannot access data correctly. Either you should pass a callback and in that callback you should have console or use axios js( promise based HTTP library)

Mohit Tilwani
  • 2,716
  • 1
  • 13
  • 13
0

move the line console.log(allresults[1].items[0].pageCount); inside the success callback. It didn't work because ajax is asynchronous and because of that your console.log is diplayed before the ajax call is finish.

your code should be something like:

  var thelink = "https://www.googleapis.com/books/v1/volumes?q=isbn:";
  var allresults = [];

  for (var i = 0; i < bookList.length; i++) {
    $.ajax({
      url: thelink + bookList[i],
      dataType: 'json',
      type: 'get',
      cache: true,
      success: function (data) {
        allresults.push(data);
        // check if it's the last result, if so check all the values inside allresult
      }
    });
  };
sheplu
  • 2,937
  • 3
  • 24
  • 21