Good day,
I have a database that contains person names, but not telephone numbers. I would like to add telephone numbers to the database. I have a commandline executable that takes a person’s name as argument and returns a telephone number.
I do a Meteor.call from the server, however it returns ‘undefined’ for each person in the forEach() loop.
I am a bit new to async programming and I suspect that the forEach loop does not wait for the commandline executable to complete. My code is given below.
Any advice would be greatly appreciated.
Best regards,
George
/server/methods.js
Meteor.methods({
'commandline_executable':function(name){
spawn = Npm.require('child_process').spawn;
command = spawn('commandline_executable',[name]);
command.stdout.on('data', function (data) { console.log('stdout: ' + data); });
command.stderr.on('data', function (data) { console.log('stderr: ' + data); });
command.on('exit', function (code) { console.log('child process exited with code ' + code); });
},
/myapp.js
if (Meteor.isServer) {
Meteor.startup(function () { // code to run on server at startup
// Populate db with names and surnames; save the file containing datajs variable in /lib
console.log('populating db');
for (i = 0; i < datajs.people.length; i++) { TelephoneDB.upsert({'name':datajs.people[i].name}, datajs.people[i]); }
// Check if person has telephone number, if not assign telephone number
var persons_without_number = TelephoneDB.find({'number':{$exists:false}});
persons_without_number.forEach( function(person) {
Meteor.call('commandline_executable',person.name,function(error,result){
if(!error){
console.log(result);
}
});
} );
});
}