What is the proper way to fire a function after multiple $http requests have finished? I have 2 options but I'm not sure which is the proper one. Note that both log 'done', after 'one' and 'two' have completed.
多个$ http请求完成后触发函数的正确方法是什么?我有2个选项,但我不确定哪个是正确的。请注意,“一”和“两”之后的“完成”日志已完成。
First, I'm just pushing all the $http requests to an array and using $q.all(promises).then
to fire the final callback, I don't remember where I saw this but it seems to be working fine(might be because my localhost is fast at processing the requests):
首先,我只是将所有$ http请求推送到一个数组并使用$ q.all(promises)。然后触发最终回调,我不记得我在哪里看到这个但它似乎工作正常(可能因为我的localhost快速处理请求):
var one = $http.get("/request/one/"),
two = $http.get("/request/two/"),
promises;
one.then(function(response){
console.log('one');
});
two.then(function(response){
console.log('two');
});
promises = $q.all([one, two]);
promises.then(function(){
console.log('done');
});
Second, I've seen it in a few tutorials, including https://egghead.io/lessons/angularjs-q-all:
其次,我在一些教程中看到了它,包括https://egghead.io/lessons/angularjs-q-all:
var one = $q.defer(),
two = $q.defer(),
promises;
$http.get("/request/one/").then(function(response){
one.resolve('one');
});
$http.get("/request/two/").then(function(response){
two.resolve('two');
});
promises = $q.all([one.promise, two.promise]);
promises.then(function(result){
console.log('done');
});
1 个解决方案
#1
2
You should definitely go with the first approach. The second one creates two unnecessary promises. $http
already returns promises, so there's no need to create two more with $q.defer()
.
你绝对应该采用第一种方法。第二个创造了两个不必要的承诺。 $ http已经返回promises,所以不需要再用$ q.defer()创建两个。
#1
2
You should definitely go with the first approach. The second one creates two unnecessary promises. $http
already returns promises, so there's no need to create two more with $q.defer()
.
你绝对应该采用第一种方法。第二个创造了两个不必要的承诺。 $ http已经返回promises,所以不需要再用$ q.defer()创建两个。