简体   繁体   中英

Use promise inside resolved promise

I am trying to get one array based on the result of another array:

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);
    });
});

It seems that my get request is working but I don't see the result

You're calling $q.all on projetsPromises before it has anything in it. You need to do that inside the handler on your previous $q.all call.

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);  //
        });                                     //
    });                                         //
});

Just for what it's worth, your for loop at the outset is what Array#map was designed to do:

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

or with an ES2015+ arrow function:

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

...assuming, of course, that result.data.ftListes is an array. :-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM