2017-05-24 71 views
0

我想基於另一個陣列的結果得到一個數組:使用承諾內解決承諾

for (var i = 0; i < result.data.ftListes.length; i++) { 
    //Get the name of the task related to the timesheet 
    tachesPromises.push(Tache.getTachebyId(result.data.ftListes[i].tacheid)); 
    // I tried to get the project here but it didn't work 
} 

//resolve promises 
$q.all(tachesPromises).then(function(taches) { 
    taches.forEach(function(el) { 
     tasks.push(el.data.tachelistes); 
     projetsPromises.push(Projet.getProjetbyId(el.data.tachelistes.projet_id)); 
    }); 
}); 

$q.all(projetsPromises).then(function(p) { 
    p.forEach(function(el) { 
     projet.push(el.data.projetsListe); 
    }); 
}); 

看來,我的GET請求工作,但我沒有看到結果

+3

請求幫助時,請縮進併合理地格式化您的代碼。圖沙爾在這個場合爲你做了。 –

回答

3

您在projetsPromises之前有任何內容,請致電$q.all。你需要這樣做裏面處理器在你以前的$q.all電話。

for (var i = 0; i < result.data.ftListes.length; i++) { 
    //Get the name of the task related to the timesheet 
    tachesPromises.push(Tache.getTachebyId(result.data.ftListes[i].tacheid)); 
    // I tried to get the project here but it didn't work 
} 

//resolve promises 
$q.all(tachesPromises).then(function(taches) { 
    taches.forEach(function(el) { 
     tasks.push(el.data.tachelistes); 
     projetsPromises.push(Projet.getProjetbyId(el.data.tachelistes.projet_id)); 
    }); 
    $q.all(projetsPromises).then(function(p) { // Moved 
     p.forEach(function(el) {    // 
      projet.push(el.data.projetsListe); // 
     });          // 
    });           // 
}); 

只是爲了它的價值,你for循環當初是什麼Array#map設計要做到:

tachesPromises = result.data.ftListes.map(function(e) { 
    return Tache.getTachebyId(e.tacheid); 
}); 

或與ES2015 +箭頭功能:

tachesPromises = result.data.ftListes.map(e => Tache.getTachebyId(e.tacheid)); 

...假設,當然,result.data.ftListes是一個數組。 :-)