0

Among a number of other assignments in an express .post call, one .push is run in a forEach(function):

var toUsers = req.body.to; // [ 'user1', 'user2' ]
toUsers.forEach(toLoop);

function toLoop(element, index, array){

    Models.User.findOne({username: element},

        function (err, user) {

            toUserId = user._id;

            console.log('to: ' + element);
            console.log('toUserId: ' + toUserId);

            story.to.push({

                user : toUserId,
                username : element,
                updated : req.body.updated

            });

    });
}

This loop above is running after the .save call though!

story.save(function(err) {

    if (err)
        res.send(err);

    res.json({ message: 'Story Created' });

});
StackThis
  • 883
  • 3
  • 15
  • 45
  • `findOne` is asynchronous! – Bergi Jul 03 '14 at 01:16
  • @Bergi how would I write this as a callback or a promise? – StackThis Jul 03 '14 at 16:34
  • Since it contains a loop, you should either use a callback library (like async.js, `async.map`) or promises (like Bluebird, `Promise.map`). Check their docs for examples and try it. If it doesn't work, [edit] your question to include your attempt. – Bergi Jul 03 '14 at 22:36

0 Answers0