在封闭的方法中在Node JS Express请求中访问POST响应数据

我在这里抨击NodeJ的学习曲线。 我有一个应用程序在节点的JS Express使用请求进行POST到另一个API。 通话正常,我的控制台日志显示正确的数据回来。 我的问题是如何从request.post(…)中获取该响应,并在发出请求的方法中使用它。

这是我的场景。 外部应用程序调用我的API。 我的API必须调用另一个API来获取一些数据来检查更新。 (我有一个API发出POST请求,以响应来自外部应用程序的POST请求。)

这是我的API中的方法,它向第三方请求一些数据。 我需要从这个POST响应中获取数据,在响应外部应用程序的POST请求之前将其返回。

exports.getUpdates = function(variable1, variable2, variable3) { request.post( 'http://myurl.exp/api//getUpdates', {json: {var1: variable1, ...}}, function (error, response, body) { if(!error && response.statusCode == 200) { console.log(body); } else {console.log(error);} } ); <I need to have this method return the response to the controller that called this method> }; 

我见过很多例子,但是他们都只是说我正在成长为仇恨的console.log()。我猜测它与callback有关,而且我没有正确处理它,但是没有一个研究已经显示了我处理callback的明确方法。 任何帮助表示赞赏。

利用callback

 exports.getUpdates = function(variable1, variable2, variable3, callback) { request.post( 'http://myurl.exp/api//getUpdates', {json: {var1: variable1, ...}}, function (error, response, body) { if(!error && response.statusCode == 200) { callback(error, response, body); } else {console.log(error);} } ); }; 

现在你可以在调用这个函数的时候传递一个callback函数:

 getUpdates(var1, var2, var3, function(error, response, body) { //stuff that you want to perform after you get response or error }); 

不过,我build议更干净的方法来做到这一点:

 exports.getUpdates = function(variable1, variable2, variable3, callback) { request.post('http://myurl.exp/api//getUpdates', {json: {var1: variable1, ...}}, callback); }; 

现在你可以在调用这个函数的时候传递一个callback函数:

 getUpdates(var1, var2, var3, function(error, response, body) { if(!error && response.statusCode == 200) { // stuff you want to do } else { console.log(error); } } });