Returned unirest response in node.js is undefined

2019-05-07 06:10发布

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.

2条回答
别忘想泡老子
2楼-- · 2019-05-07 06:28

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.

查看更多
该账号已被封号
3楼-- · 2019-05-07 06:46

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")
            }
        })
查看更多
登录 后发表回答