The key here is that I want my function to return the value I receive asynchronously from another function. Here is the structure:
const https = require('https');
function getNumPages(substr) {
let totalPages = 0;
console.log(`Before makeRequest ${totalPages}`); //0
makeRequest(substr,(numPages)=>{
console.log(`Inside callback from makeRequest${numPages}`); //79
totalPages = numPages;
});
console.log(`After makeRequest${totalPages}`); //0
return totalPages;
}
What is the best way to have getNumPages return the value that comes from makeRequest. I understand the asynchronous nature of the code, and that the return value gets executed before the makeRequest function calls its callback.
I want to be able to call getNumPages with a string, say getNumPages('Shakespeare') and makeRequest will call the API, get the number of pages of shakespeare in the db and then getNumPages to return the integer. I am aware that inside the callback to makeRequest I have the proper number of pages, but say I don't want to do work there, I just want to return it from getNumPages.