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?