Search code examples
javascriptnode.jsloopback

Attaching data from callback function inside a for loop Loopback


I´m trying to create a hook where I loop on each result from the response, find a user based on the current object and attach it as another attribute to the final response. However, the async calls are not letting me send the right response:

  Board.afterRemote('find',function(context,boards,next){
    var users = [];
    context.result.admin =[];
    var User = app.models.User;


    context.result.forEach(function(result){
      User.findOne({where:{id:result.adminId}},function(err,user){
        result.admin = user;
      });

    });
    console.log("result: "+JSON.stringify(context.result));
    next();

  });

How can I be able to add the user to each result on the context.result ?


Solution

  • Is User.findOne and asynchronous operation? If so, I would recommend using an async control flow library like async to iterate over the result and perform an asynchronous action on each item. It would look something like this:

    Board.afterRemote('find',function(context,boards,next){
        async.each(context.result, function(result, callback) {
            User.findOne({where:{id:result.adminId}},function(err,user){
              result.admin = user;
              callback(err) // Done with this iteration
            });
        }, function(err) { // Called once every item has been iterated over
            console.log("result: "+JSON.stringify(context.result));
            next();
        });
    });