我已经使用同步(http请求)调用从客户端(使用ajax)将程序转换为服务器端(Nodejs)。之后,程序花费的时间比原来长了 4 倍。
当我使用异步调用时,我得到“未定义”作为函数的返回。 所以,我尝试了两种同步调用的方式,时间都太长了
有没有好的方法可以使用异步调用在下面的函数中获取“body_return”? 或者,使用快速同步通话?
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;
}
由于 Node.js 的异步特性,您的函数会返回
undefined
。
当您实际收到响应时,您应该在 body_return
内返回 callback of request
。
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;
}
});
}
您可以使用 npm 库 sync-request-curl 来实现此目的,如下所示:
const request = require('sync-request-curl');
然后,从你的代码片段中,
//sync call-TRY.2
var body = request('POST', '(uri)', options).getBody('utf8');
var body_return = dosomething(body);
注意:我是 sync-request-curl 的作者,它包含 sync-request 中功能的子集,但利用 node-libcurl 在 NodeJS 上获得更好的性能。