如何在 angularjs 内等待多个请求完成
How to wait for multiple request to complete in angularjs
我希望在继续我的 Web 应用程序之前完全加载多个方法。为此,我做了以下 -
function getData(){
var defer = $q.defer();
$http.get("/echo/json/").success(function(data, status) {
getData2();
getData3();
$timeout(function(){
defer.resolve(data);
}, 1000);
});
return defer.promise;
}
这里,getData2() 和 getData3() 也会进行 ajax 调用。所以我必须等待这些方法完成那里的调用,然后我必须 return 承诺 main 方法。
这很好用,但给我带来了性能问题。
我还有其他方法可以做到这一点吗?
如果顺序不重要,请使用 $q.all(),如下所示:
$q.all([getData1(), getData2(), getData3()])
.then(function(result){
// result[0] is output of getData1()
// result[1] is output of getData2()
// result[2] is output of getData3()
});
但如果顺序很重要,请按如下方式在链中调用它们:
getData1()
.then(function(result1){
return getData2();
})
.then(function(result2){
return getData3();
})
.then(function(result3){
// your other codes
});
假设所有 getDataX
函数 return promises,你应该像这样链接它们:
getData()
.then(function(result){
return getData1();
})
.then(function(result1){
return getData2();
})...
我希望在继续我的 Web 应用程序之前完全加载多个方法。为此,我做了以下 -
function getData(){
var defer = $q.defer();
$http.get("/echo/json/").success(function(data, status) {
getData2();
getData3();
$timeout(function(){
defer.resolve(data);
}, 1000);
});
return defer.promise;
}
这里,getData2() 和 getData3() 也会进行 ajax 调用。所以我必须等待这些方法完成那里的调用,然后我必须 return 承诺 main 方法。
这很好用,但给我带来了性能问题。 我还有其他方法可以做到这一点吗?
如果顺序不重要,请使用 $q.all(),如下所示:
$q.all([getData1(), getData2(), getData3()])
.then(function(result){
// result[0] is output of getData1()
// result[1] is output of getData2()
// result[2] is output of getData3()
});
但如果顺序很重要,请按如下方式在链中调用它们:
getData1()
.then(function(result1){
return getData2();
})
.then(function(result2){
return getData3();
})
.then(function(result3){
// your other codes
});
假设所有 getDataX
函数 return promises,你应该像这样链接它们:
getData()
.then(function(result){
return getData1();
})
.then(function(result1){
return getData2();
})...