2017-05-24 69 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是一个数组。 :-)