我正在构建一个NodeJS应用程序(使用Sails,但我认为这无关紧要).
I've got a NodeJS app i'm building (using Sails, but i guess that's irrelevant).
在我的行动中,我有许多需要加载的对其他服务,数据源等的请求.但是,由于对回调的依赖性很大,因此在该操作返回HTML之后很长时间,我的代码仍在执行.
In my action, i have a number of requests to other services, datasources etc that i need to load up. However, because of the huge dependency on callbacks, my code is still executing long after the action has returned the HTML.
我一定会错过一些愚蠢的东西(或者不能完全避免整个异步),但是到底该如何停止我的动作呢,直到我准备好所有数据以呈现视图?!
I must be missing something silly (or not quite getting the whole async thing) but how on earth do i stop my action from finishing until i have all my data ready to render the view?!
欢呼
推荐答案很难确切说明问题所在,但这是一个猜测.假设您只有一个外部调用,您的代码应如下所示:
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 之类的库来帮助并行化请求 github/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 github/caolan/async
更多推荐
等待响应时阻止功能
发布评论