如何等待请求响应并返回值?

时间:2016-06-12 06:32:02

标签: node.js npm npm-request

当我在node.js服务器中使用请求模块时,我遇到了一些问题,例如wait和return。

我想收到一个" responseObject" requestController的值。

为了解决这个问题,我搜索了最好的方法,但我仍然没有找到它。

如何解决这个问题?

提前感谢!! :)

=============================================== ==========================

var requestToServer = require('request');

function getRequest(requestObject) {

    var urlInformation = requestObject['urlInformation'];
    var headerInformation = requestObject['headerInformation'];

    var jsonObject  = new Object( );

    // Creating the dynamic body set
    for(var i = 0; i < headerInformation.length; i++)
        jsonObject[headerInformation[i]['headerName']] = headerInformation[i]['headerValue'];

    requestToServer({
        url : urlInformation,
        method : 'GET',
        headers : jsonObject
    }, function(error, response ,body) {
        // todo response controlling
        var responseObject = response.headers;
        responseObject.body = body;
    });
}

// Controlling the submitted request
exports.requestController = function(requestObject) {
    var method = requestObject['methodInformation'];
    var resultObject = null;

    // Selecting the method
    if(method == "GET")
        resultObject = getRequest(requestObject);
    else if(method =="POST")
        resultObject = postRequest(requestObject);
    else if(method == "PUT")
        resultObject = putRequest(requestObject);
    else if(method == "DELETE")
        resultObject = deleteRequest(requestObject);

    console.log(JSON.stringify(resultObject));
}

1 个答案:

答案 0 :(得分:3)

您可以通过以下方式使用callbacks

function getRequest(requestObject, callback) {
    // some code
    requestToServer({
       url : urlInformation,
       method : 'GET',
       headers : jsonObject
    }, function(error, response ,body) {
       // todo response controlling
       var responseObject = response.headers;
       responseObject.body = body;
       callback(responseObject);
    }); 
}

// Controlling the submitted request
exports.requestController = function(requestObject) {
   var method = requestObject['methodInformation'];

   // Selecting the method
   if(method == "GET")
      getRequest(requestObject, function(resultObject){
          console.log(JSON.stringify(resultObject));
      });

   //some code
}

希望,这有帮助。