1

I am trying to use async to collect some additional data to my array.

for this purpose ive created the following:

    User_has_academy_module.findAll({
    include: [{model: Module, include: [Category, ModuleType]}],
    where: {academy_team_id: team_id, user_id: user_id}
}).then(function (modules) {
    var i = 0;
    async.map(modules, function (module,moduleCallback) {
        var act = Academy_Attempt.build();
        if(module.dataValues.is_complete == 1){
            act.findByUserTeamAndModule(module.dataValues.user_id, module.dataValues.academy_team_id, module.dataValues.module_id, function (result) {
                module.dataValues.academy_attempt = result;
                moduleCallback(null, module);

            }, function (error) {

            })
        }
    });
    onSuccess(modules);
})

as you can see from the above i first collect an array called modules that i need loop over for each of these modules i want to find additonal data if a value called is_complete == 1

once it finds a value it should set the module.dataValues.academy_attempt = result

Once all of the modules have been iterated it should call the callback (onSuccess) and return the modules.

However it runs onSuccess before the async call.

So my question is what am i doing wrong and how can fix it?

Marc Rasmussen
  • 19,771
  • 79
  • 203
  • 364

1 Answers1

3

You need to run onSuccess in a completion callback to async.map. The first callback is the iterator, runs for every mapped element; the second callback (which you currently aren't using) runs after all iterations have completed.

async.map(modules, function (module,moduleCallback) {
    //...
}, function(err, modules) {
    onSuccess(modules);
});

Currently, your code queues up the asynchronous map job and then runs onSuccess without waiting for map to finish (or even start).

apsillers
  • 112,806
  • 17
  • 235
  • 239