asynchronous - NodeJS : problem with request asynchronous, 同步,api

标签 asynchronous request node.js synchronous

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

这是类中的一个方法:

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/

相关文章:

node.js - 在fs.readdir函数外部访问变量

javascript - 如何在 JavaScript 中等待谓词条件变为真?

Node.js sequelize 关联包括

javascript - nodejs return callback() 和 just callback() 有什么区别

javascript - 用 mongoose 更新子字段

java - Spring MVC 异步任务同步运行

javascript - Ajax异步: false freezes web page during loading in slow network

c# - 如何拦截WCF Web方法请求?

javascript - 图像 src(通过 javascript)chrome/firefox 之间不一致

php - Laravel 中未定义的类请求