How do I use variable value outside of your callback? Javascript

Asked

Viewed 202 times

0

I’m trying to get the HTML of any URL (Google for example), to use it in my front end. First, I try my server.js Node with Express to 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 by giving her console.log below, she’s still null, and I can’t use the contents of the body variable.

Tips?

1 answer

2


plays the res.send({ret: retorno}) into the request callback function

what is happening is that request is asynchronous when the Node engine is running 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, ie no value has been assigned to the null variable

if you analyze the parameters of the request function there are 2 arguments request(url, callback)

the first is the url ue 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 so you have to put es.send(return)` inside the callback function for your program returns only when the asynchronous call is completed

Give a searched in callback functions , Promise, await/async

Browser other questions tagged

You are not signed in. Login or sign up in order to post.