我在尝试将异步函数转换为同步函数时遇到问题。
这是类中的一个方法:
doPost: function(call, data) {
var uri = 'http://localhost/api/'+call;
var api = http.createClient(80, 'localhost');
var domain = 'localhost';
var request = api.request("POST", uri,
{'host' : domain,
'Content-Type' : 'application/x-www-form-urlencoded',
"User-Agent": this.userAgent,
'Content-Length' : data.length
});
request.write(data);
request.end();
request.on('response', function (response) {
response.on ('data', function (chunk) {
sys.puts(chunk);
try {
var result = JSON.parse(chunk);
//------------ the problem
return HOW_TO_RETURN_RESULT;
//------------ /the problem
}catch (err) {
return {'ok': 0, 'err': err}
}
});
});
},
想这样使用这个功能:
result = obj.doPost('getSomeData.php', '&data1=foo&data2=bar');
问候
汤姆
最佳答案
只需使用回调即可。
obj.doPost('getSomeData.php', '&data1=foo&data2=bar', function(data) {
result = data;
});
关于asynchronous - NodeJS : problem with request asynchronous, 同步,api,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4639241/