Node.js: REST client returns the value before it&#

2019-09-03 03:43发布

问题:

I am trying to use the node-rest-client REST client in Node.js.

When I use the following code, it returns null but the console prints the response after that. How can I make synchronized calls using the REST client?

var postRequest = function(url, args) {
  var client = new Client();
  var responseData = {};

  client.post(url, args, function(data, response) {
    responseData = data;
    console.log(responseData);
  });

  return responseData;
};

回答1:

The module internally uses Node.js' native HTTP methods, so they aren't synchronous. You can't turn an asynchronous function into a synchronous one, so you need to use a callback:

var postRequest = function(url, args, callback) {
  var client = new Client();
  var responseData = {};
  client.post(url, args, function(data, response) {
    responseData = data;
    callback(responseData);
  });
};

Then you can call the function like this:

postRequest(url, args, function(response) {
  // response
});