0

i have the following routing function:

router.route('/api/teamUsersWithStat/:team_id')
.get(function (req, res) {
    var user_stat = academy_team_user_stat.build();
    user_stat.usersByTeam(req.params.team_id, function (result) {
        if (result) {
            async.each(result, function () {
                var i = 0;
                user_stat.findModulesTaken(res.user_id, res.team_id, function (modules) {
                    result[i].modules = modules;
                    i++;
                });
            }, res.json(result))

        } else {
            res.status(401).send("Team not found");
        }
    }, function (error) {
        res.send("Team not found");
    });
});

as you can see im using the async.each method to collect additional data to my existing array.

However the res.json(result) is called without it running the actual loop.

(i can tell this as in my javascript i am debugging the response).

So what am i doing wrong?

2 Answers 2

3

You're calling your res.json method straight away, you're also reinitializing i inside the loop so it's always 0.

Also, each requires a callback in order to procede to the next iteration.

The following is how I'd do it:

async.each(result, function (r, callback) {
    user_stat.findModulesTaken(res.user_id, res.team_id, function (modules) {
        result[result.indexOf(r)].modules = modules;
        callback();
    });
}, function(err) {
    if(err)
        return res.json(err);
    res.json(result);
});
Sign up to request clarification or add additional context in comments.

Comments

0

res.json(result) is called as a function, and therefore invoked immediately. To make sure res.json is invoked after the async.each(), you need to pass a function as callback:

async.each(result, function () {
    ...
}, function(err) {
    if(!err) res.json(result);
));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.