Node.js的:它返回之前REST客户端返回值 [英] Node.js: REST client returns the value before it's returned

查看:154
本文介绍了Node.js的:它返回之前REST客户端返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用节点休息客户端 REST客户端节点。 JS。

当我用下面的code,它返回,但在控制台打印后的反应。我怎样才能让使用REST客户端同步调用?

  VAR postRequest =功能(URL,参数){
  VAR的客户=新客户();
  变种responseData = {};  client.post(URL,ARGS,功能(数据,响应){
    responseData =数据;
    的console.log(responseData);
  });  返回responseData;
};


解决方案

该模块内部使用Node.js的本地的HTTP方法,所以它们不是同步的。你不能把一个异步函数转换为同步,所以你需要使用一个回调:

  VAR postRequest =功能(URL,指定参数时,回调){
  VAR的客户=新客户();
  变种responseData = {};
  client.post(URL,ARGS,功能(数据,响应){
    responseData =数据;
    回调(responseData);
  });
};

然后就可以调用该函数是这样的:

  postRequest(URL,指定参数时,函数(响应){
  //响应
});

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

解决方案

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

这篇关于Node.js的:它返回之前REST客户端返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆