[英]How to make a FAST synchronous request on Node.js
I have converted a program using synchronous(http request) call from client side(using ajax) to server side(Nodejs). 我已经从客户端(使用ajax)到服务器端(Nodejs)使用sync(http请求)调用转换了程序。 After that, the program takes 4 times longer than it took.
在那之后,该程序花费的时间是它的4倍。
I get 'undefined' as return of the function when I use asynchronous call. 使用异步调用时,我得到“未定义”作为函数的返回。 So, I have tried two ways of synchronous call, and both takes too long time.
因此,我尝试了两种同步调用方式,并且都花费了很长时间。
Is there good ways to get 'body_return' in the function below, using async call? 是否可以使用异步调用在下面的函数中获取“ body_return”的好方法? Or, using FAST sync call?
还是使用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;
}
Your function returns undefined
because of asynchronous nature of node.js. 由于node.js的异步特性,您的函数返回
undefined
。 You should return body_return
inside callback of request
when you actually get the response. 实际获得响应时
callback of request
在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;
}
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.