【问题标题】:NodeJS: problem with request asynchronous, synchronous, apiNodeJS:请求异步,同步,api的问题
【发布时间】:2011-06-06 01:42:17
【问题描述】:

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

这是类中的一个方法:

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

问候

汤姆

【问题讨论】:

    标签: asynchronous request node.js synchronous


    【解决方案1】:

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

    根本做不到。

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

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

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

    【讨论】:

    • 我在 node.js 中读到了“promises”,但找不到任何适合我的代码的示例。
    • Promise 几乎是伪装的回调
    • 另外,即使 Promise 做了你想要的,node.js 也没有:japhr.blogspot.com/2010/04/no-more-promises-in-nodejs.html
    • 他们现在是EventEmitters。
    • @Jakob 谢谢 - 我无缘无故地与异步作斗争:)
    【解决方案2】:

    只需使用回调。

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

    【讨论】:

    • 这并没有把它变成一个同步函数。它的作用恰恰相反。 (但另一方面,这当然是应该如何使用这个功能)。
    猜你喜欢
    • 2017-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-31
    • 2013-10-23
    • 2014-09-12
    • 1970-01-01
    相关资源
    最近更新 更多