javascriptnode.jsresponseunirest

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.


Solution

  • Someone from reddit taught me how to add a callback, and now it works as I want it. The complete code is:

    // GET a resource
    function requestExc(callback) {
        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)
                callback(res.error, null)
            } else {
                console.log('GET response', res.body)
                callback(null, res.body)
            }
        })
    }
    

    and I call it

    var response = requestExc(function(error, res) {
                console.log("date array is " + dateArray)
                if (error === null) {
                    respondToSender(res["rate"], res["date"], sender, queryDict)
                } else {
                    sendTextMessage(sender, "Imi pare rau, dar am intimpinat o problema in comunicarea cu BNR")
                }
            })