我是Node和Express的新手,在从一个函数获取数据时遇到麻烦,以var作为另一个函数传递。我认为这是因为我没有正确处理回调和异步的东西,但是我会很感激。“
希望代码可以解释。我试图从URL中检索一些JSON数据,并将其传递给router.get函数的render()方法。但是,不会发送任何内容(“未定义”)。但是,当我单独运行getData()函数时,它返回正确的数据,如上所述,我认为这是因为我没有正确处理异步内容。
function getData(cid){
var request = require("request");
var cid ='XXXXXX' // hard code temp
var baseUrl = "someurl.com"
var apiKey = "XXXXXX"
var cUrl = baseUrl+cid+'?api_key='+apiKey
request({
url: cUrl,
json: true
}, function (error, response, body) {
if (!error && response.statusCode === 200) {
console.log(body._embedded.assets); //Print the json response
return body._embedded.assets
}
});
}
/* GET home page. */
router.get('/', function(req, res) {
var LiveCards = getData()
var cID = (req.query.cID
? req.query.cID
: '14d115ff-1db7-4a6f-8648-ea64bc1a6597')
var limit = Number(req.query.limit)
res.render('index', {
title: 'Cards',
cards: LiveCards.slice(0,limit), <--- returning undefined at the moment
limit: limit,
activateSharetools: activateSharetools,
cID: cID,
cardsHeader: req.query.cardsHeader,
});
});
任何指导意见。
答案 0 :(得分:1)
请求是异步函数,您需要添加回调以获取数据并在完成请求后执行它,如下所示:
function getData (cid, callback) {
var request = require("request");
var cid = 'XXXXXX';
var baseUrl = "someurl.com";
var apiKey = "XXXXXX";
var cUrl = baseUrl + cid + '?api_key=' + apiKey
request({url: cUrl, json: true}, callback);
}
router.get('/', function (req, res) {
var cID = req.query.cID ? req.query.cID : '14d115ff-1db7-4a6f-8648-ea64bc1a6597');
var limit = Number(req.query.limit);
getData(cID, function (error, response, body) {
if (!error && response.statusCode === 200) {
res.render('index', {
title: 'Cards',
cards: body._embedded.assets.slice(0, limit), <--- returning undefined at the moment
limit: limit,
activateSharetools: activateSharetools,
cID: cID,
cardsHeader: req.query.cardsHeader,
});
} else {
throw error;
}
});
});