且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

等待响应时阻止功能

更新时间:2023-01-23 18:25:25

很难确切说明问题所在,但这是一个猜测.假设您只有一个外部调用,您的代码应如下所示:

It's hard to tell exactly what the problem is but here is a guess. Assuming you have only one external call your code should look like this:

exports.myController = function(req, res) {

    longExternalCallOne(someparams, function(result) {

       // you must render your view inside the callback
       res.render('someview', {data: result});
    });

    // do not render here as you don't have the result yet. 

}

如果您有两个以上的外部呼叫,您的代码将如下所示:

If you have more than two external calls your code will looks like this:

exports.myController = function(req, res) {

    longExternalCallOne(someparams, function(result1) {

       longExternalCallTwo(someparams, function(result2) {

         // you must render your view inside the most inner callback
         data = {some combination of result1 and result2};
         res.render('someview', {data: data });

       });

       // do not render here since you don't have result2 yet

    });

    // do not render here either as you don't have neither result1 nor result2 yet. 

}

如您所见,一旦您进行了多个长时间运行的异步调用,事情就会开始变得棘手.上面的代码仅用于说明目的.如果您的第二个回调依赖于第一个回调,那么您需要类似的东西,但是如果longExternalCallOne和longExternalTwo彼此独立,则应该使用 async 之类的库来帮助并行化请求 https://github.com/caolan/async

As you can see, once you have more than one long running async call things start to get tricky. The code above is just for illustration purposes. If your second callback depends on the first one then you need something like it, but if longExternalCallOne and longExternalTwo are independent of each other you should be using a library like async to help parallelize the requests https://github.com/caolan/async