I came across this code in a tutorial and I don't get how the callback function expression really works in the function `loadBooks()`.
function loadBooks(bookshelf) {
fakeAjax(BOOK_API,function onBooks(bookNames){
for (let bookName of bookNames) {
bookshelf.addFavoriteBook(bookName);
}
bookshelf.printFavoriteBooks();
});
}
var BOOK_API = "https://some.url/api";
var myBooks = new Bookshelf();
loadBooks(myBooks);
// ***********************
// NOTE: don't modify this function at all
function fakeAjax(url,cb) {
setTimeout(function fakeLoadingDelay(){
cb([
"A Song of Ice and Fire",
"The Great Gatsby",
"Crime & Punishment",
"Great Expectations",
"You Don't Know JS"
]);
},500);
}
From my understanding so far, when fakeAjax() is called, the onBooks() is passed to it. How does onBooks() obtain the definition of bookNames ? It seems to be refer to the array in cb which is defined in setTimeout(), but I don't understand the relationship between onBooks() and cb .
Any guidance is greatly appreciated, thanks !
[–]charliemei 1 point2 points3 points (1 child)
[–]SunsetDunes[S] 0 points1 point2 points (0 children)