Nodejs请求后跟请求 - 同步问题

时间:2016-04-11 17:29:20

标签: javascript node.js asynchronous request synchronous

我是回调地狱世界的新手,并且已经陷入困境。我正在做一些分析工作,所以每次调用一个函数时,我都会调用一个函数来执行request.post来记录我们服务器上的请求。但是,在每个原始函数中,都会生成一个request.get来返回一些信息。所以,我实际上是在调用一个函数,该函数在另一个需要在该函数之后发出请求的函数内部发出请求。代码本身比我刚才描述的要复杂得多(并且复杂,我的意思是冗长而烦人),所以这里是愚蠢的版本:

function myFunction(x, y, callback) {
    // variable declarations
    postFunction(a, b);
    // other logic for the function
    request.get(url, function(error, response, body) {
        // request code here
        callback(somedata, otherFunctionThatDoesntMatterHere(blah));
    });
}

function postFunction(a, b) {
    // other logic for the function
    var dataToSend = "XML HERE";
    request.post({
        url: url,
        body: dataToSend,
        headers: {'Content-Type' : 'text/xml'},
        function(error, response, body) {
            if (error) {
                console.log(error);
            }
            else if (response.statusCode !== 200) {
                console.log('Invalid Status Code Returned:', response.statusCode);
            }
            else if (!error && response.statusCode == 200) {
                console.log('POST RESPONSE: ', body);
            }
        }
    );
}

现在发生的事情是post函数在main函数结束之前没有返回。我知道这是节点异步的一部分,但我希望这些是同步执行的。我很确定我可以通过向post函数添加回调来解决这个问题,但我不确定如何。我尝试了很多不同的方法,但我担心我并不完全理解这一切是如何运作的。提前感谢您提供任何帮助!

1 个答案:

答案 0 :(得分:0)

如果你真的希望它是同步的,那么是的,你需要在postFunction中添加一个回调。

例如:

function myFunction(x, y, callback) {
 // variable declarations
 postFunction(a, b, function(err) {
   // other logic for the function
   //maybe check if "err" has a value here
    request.get(url, function(error, response, body) {
      // request code here
      callback(somedata, otherFunctionThatDoesntMatterHere(blah));
    });
 });

}

function postFunction(a, b, next) {
 // other logic for the function
 var dataToSend = "XML HERE";
 request.post({
    url: url,
    body: dataToSend,
    headers: {'Content-Type' : 'text/xml'},
    function(error, response, body) {
        if (error) {
            console.log(error);
            next(error);
        }
        else if (response.statusCode !== 200) {
            console.log('Invalid Status Code Returned:', response.statusCode);
            next('Invalid Status Code Returned:' + response.statusCode);
        }
        else if (!error && response.statusCode == 200) {
            console.log('POST RESPONSE: ', body);
            next(null);
        }
    }
 );
}

这会将你想要触发的其余代码放在postFunction的回调中,要求它在其他任何东西触发之前先完成。当然,这将增加函数的整体运行时间,因为它必须在继续运行之前等待。如果您正在执行CPU密集型任务,请小心锁定事件循环。

另外,为了对抗回调地狱的丑陋,你可以使用像async-waterfall这样的东西来逐个链接函数:https://www.npmjs.com/package/async-waterfall

相关问题