【发布时间】: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