H
H
hackerskater2016-06-16 01:55:19
Node.js
hackerskater, 2016-06-16 01:55:19

How to output variable from function, nodejs curl replacement?

In general, I've been sitting for three hours and I can't figure it out.
Here is the body variable

var options = {
     url: 'https://maps.googleapis.com/maps/api/timezone/json?location=' + latitude + ',' + longitude + '&timestamp=1331161200&key=' + googleApiKey,
     method: 'GET'
}
request(options, function (error, response, body) {
              if (!error && response.statusCode == 200) {
                                console.log(body);
         }
          				
});

Everything clearly displays an object that is easily parsed
{
   "dstOffset" : 0,
   "rawOffset" : 14400,
   "status" : "OK",
   "timeZoneId" : "Europe/Moscow",
   "timeZoneName" : "Moscow Standard Time"
}

And now the very essence is outside this function, I cannot use the body object, I tried to do return body. I tried to make an empty response variable outside the function and then response = body, but all to no avail. How can I work (parse) this object outside the function? I ask you to help a junior coder. The head is already exploding.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dronbas, 2016-06-16
@Dronbas

What for?
The request is executed asynchronously, access to the body is available only after receiving a response.

function handleBody(body){
     console.log(body);
     ...
}
request(options, function (error, response, body) {
              if (!error && response.statusCode == 200) {
                                handleBody(body);
         }
          				
});

I don't know the task, maybe it's worth thinking in the direction of promises.
function myRequest(options){
   return new Promise(function(resolve,reject){
       request(options, function (error, response, body) {
           if (!error && response.statusCode == 200) {
               return resolve(body)
           }
           //@todo handle errors
           reject()
       });
   });
}
myRequest(options).then(function(body){
   //тут теперь продолжается работа с body
}).catch(function(err){
   //code
})

A
Alexey P, 2016-06-16
@ruddy22

event driven development.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question