node.js中返回的unirest响应未定义 [英] Returned unirest response in node.js is undefined

查看:115
本文介绍了node.js中返回的unirest响应未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究facebook bot,但我绝不是node.js开发人员,这是我第一次使用它,因为我想离开我的舒适区一点点。

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.

这是我的请求函数

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
}

所以我试图得到它的结果t

so I am trying to get it's result

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

然后采取相应行动

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

但是当变量到达respondToSender时,它总是未定义的。

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

 TypeError: Cannot read property 'rate' of undefined

我也试过Json.parse(),但它也是一样的。

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

推荐答案

reddit的某个人教会了我如何添加一个回调,现在它可以按我的意愿运行。完整的代码是:

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)
        }
    })
}

我称之为

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")
            }
        })

这篇关于node.js中返回的unirest响应未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆