0

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.

sco
  • 367
  • 3
  • 14
  • 2
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Carcigenicate May 18 '18 at 22:07
  • In short, you simply can't synchronously return the value. The best you can do is return a promise for the value. Anything that relies on an asynchronous operation must itself be asynchronous. – CRice May 18 '18 at 22:07

2 Answers2

0

just return a promise, it is a only way.

but... You can make it look like a syncronous code using async/await it will just use promise under the hood anyway. but it will look and behave just like You want to (I think)

user2675118
  • 121
  • 1
  • 5
0

You could use async/await syntax

async function getNumPages(substr) => {
    const result = await makeRequest(substr);
    return result;
}
Todd C
  • 66
  • 4