-1

I am aware of this stackoverflow answer and I have been using it to help me. However something weird happens when I apply the code to my situation. It seems that the wrapAsync function, called execSync in my code, runs and outputs what it is supposed to; however, it just finished last as it did before i had the wrapAsync in place.

The code

Meteor.methods({
  'distinctSpecs'({}){
    console.log("called");
    var json_categories_clean   =   [];
    var execSync                =      
      Meteor.wrapAsync(require("child_process").exec, 
                       require("child_process"))
    var returned_data           =   
      execSync(
        "mongo products --eval \"var collection='laptops', outputFormat='json'\" variety.js", 
        { cwd:"/home/jonathan/Documents/variety-master"}, 
        (err, stdout, stderr) => {
          if (err) {
            console.error(err);
            console.log(stdout);
            console.log(stderr);
            return;
          }
          console.log("waited for this");
          var     json_categories         =   
            JSON.parse(stdout.substring(
              stdout.indexOf('[', stdout.indexOf('[')+1),
              stdout.lastIndexOf(']')+1));     

          for (var x=0; x < json_categories.length; x++) {
            json_categories_clean.push(json_categories[x]["_id"])
          }
          console.log("returning inner");
          return json_categories_clean;
        });
    console.log("returning outer");
    return returned_data;
  }
});

**The output **

 called 
returning outer 
waited for this 
returning inner
Community
  • 1
  • 1
jped
  • 486
  • 6
  • 19
  • I don't think you're supposed to pass a callback into `execSync`. Try without, I guess Meteor isn't wrapping correctly if you pass the wrong number of arguments. – Bergi Aug 24 '16 at 00:08

1 Answers1

1

After formatting your code it's pretty clear that you are invoking wrapAsync wrong:

Meteor.wrapAsync(require("child_process").exec, 
                       require("child_process"))

you probably want:

const exec = Npm.require("child_process").exec;
Meteor.wrapAsync(a, b, function(callback) {
  exec(a, b, function(err, stdout, stderr) {
    callback(err, stdout);
  });
});

The last parameter to the function you wrap needs to be a function that takes an error and a result as parameters (and nothing else).

Also, once you have the async function, you don't provide a callback anymore. You are waiting for the return instead.

Christian Fritz
  • 20,641
  • 3
  • 42
  • 71