我有尝试将异步函数转换为同步的问题。NodeJS:请求异步,同步,api的问题
这里是从类中的方法:
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');
Reagards
汤姆
我读了node.js中的“promise”,但找不到适合我的代码的任何示例。 – Tom 2011-01-09 13:14:10
承诺几乎是变相的回调 – Jakob 2011-01-09 13:16:34