Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returned unirest response in node.js is undefined

I am working on facebook bot, but I am in no way a node.js developer, this being my first time in using it, because I wanted to get out of my comfort zone for a little bit.

This is my request function

function requestExc() {
    var resDictionary = {} 
    unirest.get("http://openapi.ro/api/exchange/" + queryDict["code"] + ".json")
    .query({"date" : queryDict["date"]})
    .end(function(res) {
        if (res.error) {
            console.log('GET error', res.error)
        } else {
            console.log('GET response', res.body)
            resDictionary["rate"] = res.body["rate"]
            resDictionary["date"] = res.body["date"]
        }
    })

    console.log("resDictionary IS " + resDictionary)
    ///prints resDictionary IS [object Object]
    return resDictionary
}

so I am trying to get it's result

var response = requestExc()
if (response !== null) {
    respondToSender(response, sender)
}

and then act accordingly

function respondToSender(res, sender) {
    console.log("RES IS " + res)
    //prints RES IS [object Object]
  if (res["rate"] === null) {
        //do stuff
  }
}

but when the variable gets to the respondToSender it's always undefined.

 TypeError: Cannot read property 'rate' of undefined

I've also tried with Json.parse() but it's the same thing.

like image 537
trusk Avatar asked Feb 06 '23 17:02

trusk


1 Answers

Ok, the problem is unirest (like many node.js modules) works asynchronously meaning that your code is quite probably executed in this order:

var response = requestExc() // request is sent first, ok
if (response !== null) {    // this is done second
    respondToSender(response, sender)
}
                            // the response arrived third, when it is not needed

So to deal with such stuff, you have to use callbacks/end method. See the example here:

unirest.post('http://mockbin.com/request')
.query('name=nijiko')
.query({
  pet: 'spot'
})
.end(function (response) {
  console.log(response); // this is where you should use respondToSender
});

The console.log(response); is launched only when reply came and that's what you want.

like image 94
YakovL Avatar answered Feb 11 '23 01:02

YakovL