Thursday, 7 May 2020

NodeJS wait on execution of a method in a loop

So I am working with the goodreads API and I want to do a search for a book based on the title.The gooodreads API is a little awkward, so to get all of the data I want you have to perform two separate query, the second relies on data from the first.So the program is hitting the outer callback with an empty list send that and then the forEach loop finshes and all the data is received but not sent to the client.So what is the simplest way for me to modify the below code so that the callback waits for the loop to complete before exiting? I have been tearing my hair out trying to get promises and callbacks to work and have not had any success.Thanks for the help.searchGoodreads = function(title, callback) { var apiInitialSearchEndPoint = `https://www.goodreads.com/search/index.xml?key=${process.env.key}&q=${title}` var booksData = []; axios.get(apiInitialSearchEndPoint) .then(response => { xmlParser.parseString(response.data, (err, res) =>{ var data = JSON.parse(JSON.stringify(res)); var books = data.GoodreadsResponse.search[0].results[0].work; books.forEach((book) => { extractData(book, (parsedData) => { // I want the program to wait for this execution to be completed booksData.push(parsedData); console.log("Inner List"); console.log(booksData); }); }); //This will be completed first console.log("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"); console.log(booksData); console.log("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"); callback(null, JSON.stringify(booksData)); }); }) .catch(error => { console.log(error); callback(error, null); }); } const extractData = (message, callback) => { var goodReadsID = message.best_book[0].id[0]._; var advancedSearch = `https://www.goodreads.com/book/show/${goodReadsID}.xml?key=n0mstayRjsbdLBxIiBcGg`; axios.get(advancedSearch).then(response => { xmlParser.parseString(response.data, (err, res) =>{ var advancedData = JSON.parse(JSON.stringify(res)); var title = message.best_book[0].title[0]; var cover = message.best_book[0].image_url[0]; var num_pages = advancedData.GoodreadsResponse.book[0].num_pages[0]; var jsonData = { "GoodReadsID" : goodReadsID, "Title" : title, "Cover" : cover, "num_pages" : num_pages }; callback(jsonData); }); }) .catch(error => { console.log(error); callback(error); }); }

Submitted May 07, 2020 at 06:04PM by kopo222

No comments:

Post a Comment