0

I am executing a Meteor method within a forEach function, and pushing the result of each method (a new id) into an array that is then used for other purposes. I can get see each new id created (the resultfrom each method). However, the console is returning what appears to be an array of index numbers, rather than an array of new ids.

CODE EDITED TO ADDRESS ANSWER BELOW In event handler, with two documents selected:

var selectionsFinal = [];
selections.forEach(function(v, selectionsFinal) {
    Meteor.call('copy', v, function(error, result) {
        if(error) {
            console.log(error);
        } else {
            console.log("Result: ", result); //properly returns new id
            selectionsFinal.push(result);
            console.log("SelectionsFinal: ", selectionsFinal); // properly returns array of 2 new ids
        }
    });
    console.log("SelectionsFinal: ", selectionsFinal); //should return array of new ids, returns []
});
console.log("Selections Final: ", selectionsFinal); //should return array of new ids, returns []

Method

copy: function(v) {
    check(v, String);

    var valuation = Valuations.findOne({_id:v},{fields:{_id:0});
    return Valuations.insert(valuation)
}
Michel Floyd
  • 18,793
  • 4
  • 24
  • 39
Bren
  • 273
  • 1
  • 18

1 Answers1

0

Your pattern is going to be extremely slow and, as you've already discovered, hard to debug. Looping over a Meteor.call() is not recommended because of the numerous server round-trips.

Instead of:

var selectionsFinal = [];
selections.forEach(function(v, selectionsFinal) {
    Meteor.call('copy', v, function(error, result) {})
});

Do:

Meteor.call('bulkCopy',selections,function(error,result){});

Do the array push in the method itself and then return the whole array.

Michel Floyd
  • 18,793
  • 4
  • 24
  • 39