2016-08-23 83 views
-1

我知道this stackoverflow答案,我一直在使用它来帮助我。 但是,当我将代码应用于我的情况时,会发生一些奇怪的事情。 似乎在我的代码中名为execSync的wrapAsync函数运行并输出它应该是的;不过,它刚刚完成了最后的工作,就像我之前使用wrapAsync一样。流星WrapAsync异步工作

代码

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; 
    } 
}); 

**的**输出

called 
returning outer 
waited for this 
returning inner 
+0

我不认为你应该把回调传递给'execSync'。尝试不,我猜如果你传递错误的参数数目,流星不会正确包装。 – Bergi

回答

1

格式化你的代码后,很明显,你是调用wrapAsync错误:

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

你可能想要:

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

你包装的函数的最后一个参数需要是一个函数,它将一个错误和一个结果作为参数(而不是别的)。

此外,一旦你有异步功能,你不再提供回调。相反,你正在等待回报。