jeudi 27 juillet 2017

Multiple Promises in Ember won't resolve in the template

I'm stuck trying to return the value of a bunch of promises.

To explain the situation: there are 4 models - the students in a group have a score for each objective.

So I've made a component into which I pass an objective and the group. The component then handles the requests to the store to look up each student's score for that objective, and return the average.

The code seems to work, the console.logs give me exactly what I want, right up to the end, but the promises won't resolve into the template - I get the { object Object }, which I believe is the unresolved promise.

Something I'm missing here? Is there an extra step needed when waiting for multiple promises to resolve?

I appreciate this is a little specific, when I understand the answer I'll try and rephrase the question.

Component Code:

    averageScore: Ember.computed(function(){
    var students = this.get('group.students');
    var objective = this.get('objective');
    var store = this.get('store');
    var _this = this;

    // Create an array of promises of each student's scores
    var promises = [];
    students.forEach((student) => {
        var studentId = student.get('id');
        var objectiveId = objective.get('id');
        var newPromise = store.queryRecord('snapscore', { 'student' : studentId, 'objective': objectiveId });
        promises.pushObject(newPromise);
    });
    // When promises resolve, find and return the average
    return Ember.RSVP.allSettled(promises).then(function(scores){
        let scoreTotal = 0;
        let scoreCount = scores.length;
        console.log("Score count is " + scoreCount);
        scores.forEach((score)=>{
            console.log("Student's score is " + score.value.get('score'));
            scoreTotal = scoreTotal + score.value.get('score');
        });
        console.log("ScoreTotal is " + scoreTotal);
        var average = scoreTotal/scoreCount;
        console.log(average);
        console.log(typeof(average));
        return average;
    });
}),

The component's template then simply returns averageScore.

Thanks




Aucun commentaire:

Enregistrer un commentaire