How to wait a request response and return the value?

☆樱花仙子☆ 提交于 2019-12-06 13:58:28

问题


When I use a request module in node.js server, I have some problem such as wait and return.

I would like to receive a "responseObject" value at requestController.

To solve this problem, I have search the best way but I still do not find it.

How can solve this problem?

Thank in advance!! :)

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

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:


You can use callbacks in the following way.

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);
    }); 
}

And

// 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
}

Hope, it helps.



来源:https://stackoverflow.com/questions/37771386/how-to-wait-a-request-response-and-return-the-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!