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

2019-09-03 03:39发布

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条回答
在下西门庆
2楼-- · 2019-09-03 04:14

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
});
查看更多
登录 后发表回答