0

我在尝试将异步函数转换为同步时遇到问题。

这是类中的一个方法:

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');

问候

汤姆

4

2 回答 2

4

只需使用回调。

obj.doPost('getSomeData.php', '&data1=foo&data2=bar', function(data) {

  result = data;

});
于 2011-01-09T13:14:28.250 回答
1

将异步函数转换为同步函数是不可能的。

根本做不到。

相反,您必须将回调传递给您的函数并以异步方式接收“返回值”。

虽然理论上,您可以编写一些代码来阻止您的函数返回,直到满足某些条件(即,直到异步操作完成),但这也需要程序能够在阻塞时在另一个线程上执行其他操作正在执行,这在节点中可能是不可能的。即使是这样,它也将是世界级的反模式和针对 node.js 的犯罪,所有事情都发生了,可能会召唤一个 velociraptor。

结论:了解如何使用异步代码。此外,您可能有兴趣阅读昨天的这个问题/答案(或者至少是答案;这个问题的措辞不是很好)。

于 2011-01-09T13:10:51.500 回答