-1

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 ?

Pablo Estrada
  • 3,182
  • 4
  • 30
  • 74

1 Answers1

1

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();
    });
});
carebdayrvis
  • 175
  • 9
  • Thanka for the answer! The find is an async opertation indeed. I just have one more question. Do I still have to call the next() function at the end of the afterRemote callback? Or is it just necessary in the cb of async.each()? – Pablo Estrada Jun 06 '16 at 22:18
  • You would want to call `next` once async.each finishes. The callback passed to the iterator lets async know that this iteration is done. Once all iterations have completed the callback you've passed to async.each will be called. That is where you would call next, since that is when all the iterations have completed. `async.each(collection, iterator, callback)` I've updated the answer to show how it would look inside the `afterRemote` callback. – carebdayrvis Jun 06 '16 at 22:25