0

I have a xhr request to get a html document and parse it.

This is the first function inside of a function

function fetchBooks() {
  const xhr = new XMLHttpRequest();
  xhr.open("GET", "url");
  xhr.onload = () => {
    console.log(xhr.status);
    if (xhr.status == 200) {
      //parse books
      book.name = book_name;
      book.id = book_id;
      book.genre = book_genre;
      book.language = book_language;
      book.date = book_date;
      books.push(book);
      console.log(book);
    }
    console.log(books);
    return books;
  } else {
    console.log(`Error: ${xhr.status}`);
  }
};
xhr.send();
}

The parent function:

function homepage() {
  //do stuff
  // the above function
  var bookss = fetchBooks();
  console.log(bookss);
}

When I run the parent function, the console will print undefined, but the console.log function in the fetchBooks function will print a dictionary of books. I also have tried to put the function below but it still won't work.

EDIT: Now I have tested fetch but how should I extract the array from it? output

ducc
  • 82
  • 8
  • 1
    Your onload is returning, not fetchBooks. See [this for details on getting values from XHR](https://stackoverflow.com/questions/20207405/pass-the-value-of-an-xhr-onload-function-globally). But also, there's no need to use XHR anymore unless you're supporting very old browsers, you ought to use [Fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API). – Zac Anger May 13 '23 at 04:30
  • Maybe I will try to use fetch – ducc May 13 '23 at 04:46

0 Answers0