【问题标题】:How to make a FAST synchronous request on Node.js如何在 Node.js 上发出 FAST 同步请求
【发布时间】:2017-05-09 08:49:44
【问题描述】:

我已经使用从客户端(使用 ajax)到服务器端(Nodejs)的同步(http 请求)调用转换了一个程序。之后,程序所需的时间是原来的 4 倍。

当我使用异步调用时,我得到“未定义”作为函数的返回。 所以,我尝试了两种同步调用方式,都耗时太长。

有没有使用异步调用在下面的函数中获取“body_return”的好方法? 或者,使用 FAST 同步调用?

function getBody(input) {

  //sync call-TRY.1
  var body_return;
  request(option, function(error, response, body) {
    if (!error && response.statusCode === 200) {

       //do something with body;
       body_return = dosomething(body);
     }
  });

  //sync call-TRY.2
  var body = sync_request('POST', '(uri)', options).getBody('utf8');
  var body_return = dosomething(body);

  //async call can't return the body in time, so this function returns undefined..

  return body_return;
}

【问题讨论】:

  • 你如何确定它需要 4 倍的时间?
  • @robertklep 我在代码之前/之后使用 Date.now() 检查了日志时间。
  • 我怀疑它与 Node.js 请求异步有关,但由于缺少上下文(客户端代码是什么样的,您请求的 URL 是什么等)它是很难说为什么 Node 代码看起来更慢。

标签: node.js asynchronous httprequest synchronous


【解决方案1】:

由于 node.js 的异步特性,您的函数返回 undefined。 当您实际收到响应时,您应该在 callback of request 中返回 body_return

function getBody(input) {

//this is async call
  var body_return;
  request(option, function(error, response, body) {
    if (!error && response.statusCode === 200) {

   //do something with body;
   body_return = dosomething(body);

   //return when you get the response
   return body_return;
 }

  });  
}

【讨论】:

  • 我已经尝试过您的解决方案。您的代码也返回未定义。我希望 'getBody()' 函数等待请求,但它不等待。
猜你喜欢
  • 2014-12-27
  • 2012-06-02
  • 1970-01-01
  • 2015-02-10
  • 2017-04-13
  • 2018-01-31
  • 2017-02-19
  • 2019-01-25
  • 2019-12-21
相关资源
最近更新 更多