1

I don't understant how to set a callback in a loop:

models.chat_user.find( {user_id: app.locals.session.user._id}, function(err, result){
    if(result.length < 1){
        chat.user = new models.chat_user({
        user_id: app.locals.session.user._id
        })
        chat.user.save();
    }
    models.chat_user.find(function(err, result){
        for(value in result){
        models.user.findOne({_id: result[value].user_id}, function(err, user){
                chat.users[value] = {};
                chat.users[value].username = user.username
                chat.users[value].mail = app.locals.user.getAvatar(user.mail, 50);
            });
        }
    })
});

I'd like to set a callback when I find all datas in my loop but I don't know how mayme with a condition on the result.lenth but that's not very clean

Thanks

1 Answer 1

3

Use async.forEach like so:

models.chat_user.find(function(err, result){
    async.forEach(result, function(value, callback) {
        models.user.findOne({_id: result[value].user_id}, function(err, user){
            chat.users[value] = {};
            chat.users[value].username = user.username
            chat.users[value].mail = app.locals.user.getAvatar(user.mail, 50);
            callback(err);
        });
    }, topLevelCallback);
});

topLevelCallback is called when all forEach iterations have called their callback, passing along any error if there was one.

Sign up to request clarification or add additional context in comments.

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.