realtek realtek - 8 days ago 5
Node.js Question

Calling https.get using nodejs from a function?

I am trying to write my first Alexa Skill and I am doing an http request which works fine, however I would like to wrap this into a function that I can call from my main code.

It is not working and I am not quite sure how I can store the response into a variable, here is my code so far:

function getValue(loc) {
var endpoint = 'URLHERE'
var something = ""
var body = ""
https.get(endpoint, (response) => {
response.on('data', (chunk) => {
body += chunk
})
response.on('end', () => {
data = JSON.parse(body)
something = data.result.node.value;
})
})
return something;
}


This is on amazon and using lambda for the functions using node.js

which I call
getValue('test')
using

var result = getValue('test')


it just returned undefined.

Any idea's? Thanks

I imagine because its an asynchronous call its not setting the value due to callback but I have tried implementing this and cannot get it to work.

Thanks

Answer

You're returning from your function before the callback of http.get, mixing Synchronous with Asynchronous behaviour.

So your function is returning something which hasn't been defined yet.

Try this instead :

function getValue(loc,cb) {
    let endpoint = 'URLHERE'
    let something = ""
    let body = ""
    https.get(endpoint, (response) => {
        response.on('data', (chunk) => {
            body += chunk
        })
        response.on('end', () => {
            data = JSON.parse(body)
            cb(data.result.node.value);
        })
    })
}

getValue(test,(result)=>{
   //do something with result here;
});