[英]AngularJs $q.all use
我正在使用多個異步調用,但確實得到了結果,但是當我想使用保存該結果的數組時,出現了很多問題,當我看時發現該解決方案正在使用$ q.all,而我以前從未使用過當我閱讀文檔時,我仍然不知道應該在哪里添加它,這是我的代碼:
FT.getFT().then(function (result) {
if(result.data.success)
{
for(var i=0; i<result.data.ftListe.length;i++)
{
// récupérer le collaborateur de la feuille de temps par son id
Compte.getComptesbyId(result.data.ftListe[i].collaborateurid).then(function(result)
{
lecollaborateur.push(result.data.col);
});
//Get the name of the task related to the timesheet
Tache.getTachebyId(result.data.ftListe[i].tacheid).then(function(result)
{
Projet.getProjetbyId(result.data.tachelistes.projet_id).then(function(result)
{
projets.push(result.data.projetsListe);
});
task.push(result.data.tachelistes);
});
// get le projet lié à cette tache par id
}
$scope.ftListe = result.data.ftListe;
$scope.task = task;
$scope.lecollaborateur = lecollaborateur;
$scope.projets = projets;
console.log(result.data.message);
}else{
console.log(result.data.message);
}
});
我可以展示$q.all()
工作原理,並為您的一個諾言編寫示例。 然后由您以相同的方式重構所有代碼。 我也可以用法語保留變量名:)
$q.all()
允許您解析作為參數提供給all()
的promise數組。 作為promise的結果,您將獲得一個數組,其中元素是您的promise的相應結果。
因此,就您而言,在您的主要結果內,創建一個如下的promise數組:
FT.getFT().then(function (result) {
if(result.data.success) {
var comptesPromises = [];
在您的for內部,而不是解決承諾,只需將所有相應的承諾添加到此數組中,如下所示:
comptesPromises.push(Compte.getComptesbyId(result.data.ftListe[i].collaborateurid));
然后在for之外,解決所有promise,並將返回值分配給模型:
$q.all(comptesPromises).then(function(comptes) {
comptes.forEach(function(el) {
lecollaborateur.push(el.data.col);
});
});
您需要注入$q
才能使用它。
我希望這有幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.