How to use variable value outside of your callback? Javascript [duplicate]
I'm trying to get the HTML from any URL (from Google for example), to use it on my front-end. First, I try on my server.js Node with Express get this HTML through the "request" module:
app.get('/geradorPreview', (req, res) =>{
var retorno = null
request('http://www.google.com', function (error, response, body) {
console.log(body) //IMPRIME CORRETAMENTE O HTML
retorno = body;
})
console.log(retorno) // imprime null
res.send({ret: retorno})
})
In the first console.log, what is printed on my terminal is the HTML I requested. So I try to assign this body content to the return variable. But when giving console.log into it next, it remains null, and I can't use the contents of the body variable.
Tips?
1 answers
Throws res.send({ret: retorno})
into the callback function of request
What is happening is that request is asynchronous when the node engine is executing its code it reads the request makes an asynchronous call and passes to the next statement, but the next statement is already console.log(retorno)
that is returning null because the asynchronous call has not yet been completed, that is, no value has been assigned to the variable null
If you parse the parameters of the request function there are 2 arguments request(url, callback)
The first is the UE url in your case is http://www.google.com
The second is the call back function which in your case is
function (error, response, body) {
console.log(body) //IMPRIME CORRETAMENTE O HTML
retorno = body;
})
When the asynchronous call is completed the call back function is executed soon you have to put the es.send ' within the callback function for your program returns only when the asynchronous call has been completed
Search callback functions, Promise, await/async