我正在调用一个函数来request.gets一些json并填写我的router.get
中的变量变量在callFunc函数中获取它们的值但在router.get
中它们是未定义的如何将它们设置为全局,以便我可以在request.get中分配值并使用router.get中的值
var title;
var headline;
router.get('/test/code/:code', function(req, res, next){
var procedure = "EXECUTE procedureName 999, 'userName', "+req.params.code
callFunc(procedure)
res.render('display', {
title: title, // <-- This value here is undefined
descritpion: headline, // <-- This value here is undefined
var1: 'block sidebar',
var2: 'block content',
image: 'http://baidun.com/wp-content/uploads/2013/06/SI_RM_1070bw-900x598.jpg',
url: 'https://www.youtube.com/watch?v=ZB_VPDXAhKU'
})
})
function callFunc(procedure){
request.get('http://myWebservice.com/myService.asmx/myServiceDB?callback=&userName=username&procedureName='+procedure, function(req, res, body){
var testValue = body.slice(1, -2);
var result1 = JSON.parse(testValue);
var result2 = JSON.parse(result1);
title = result2.jobSelect[0].jobTitle;
headline = decodeURI(result2.jobSelect[0].jobHeadline);
console.log(title) // <-- I get the right value here
console.log(headline) // <-- I get the right value here
})
}
答案 0 :(得分:2)
不应该需要对数据进行全局范围调整。您可以简单地使用带回调的callFunc,然后传回数据对象。
router.get('/test/code/:code', function(req, res, next){
var procedure = "EXECUTE procedureName 999, 'userName', "+req.params.code
callFunc(procedure, function(obj) {
res.render('display', {
title: obj.title,
descritpion: obj.headline,
var1: 'block sidebar',
var2: 'block content',
image: 'http://baidun.com/wp-content/uploads/2013/06/SI_RM_1070bw-900x598.jpg',
url: 'https://www.youtube.com/watch?v=ZB_VPDXAhKU'
});
});
});
function callFunc(procedure, callback){
request.get('http://myWebservice.com/myService.asmx/myServiceDB?callback=&userName=username&procedureName='+procedure, function(req, res, body){
var testValue = body.slice(1, -2);
var result1 = JSON.parse(testValue);
var result2 = JSON.parse(result1);
var obj = {
title: result2.jobSelect[0].jobTitle,
headline: decodeURI(result2.jobSelect[0].jobHeadline)
};
callback(obj);
})
}
答案 1 :(得分:1)
一种简单的方法就是使用res.render作为回调。
var title;
var headline;
router.get('/test/code/:code', function(req, res, next){
var procedure = "EXECUTE procedureName 999, 'userName', "+req.params.code
callFunc(procedure, function(title, headline) {
res.render('display', {
title: title,
descritpion: headline,
var1: 'block sidebar',
var2: 'block content',
image: 'http://baidun.com/wp-content/uploads/2013/06/SI_RM_1070bw-900x598.jpg',
url: 'https://www.youtube.com/watch?v=ZB_VPDXAhKU'
})
})
})
function callFunc(procedure, cb){
request.get('http://myWebservice.com/myService.asmx/myServiceDB?callback=&userName=username&procedureName='+procedure, function(req, res, body){
var testValue = body.slice(1, -2);
var result1 = JSON.parse(testValue);
var result2 = JSON.parse(result1);
title = result2.jobSelect[0].jobTitle;
headline = decodeURI(result2.jobSelect[0].jobHeadline);
cb(title, headline);
})
}