流星回调到Meteor.call回调中的sys.exec

Dav*_*mes 4 asynchronous callback meteor

我有一个事件触发Metor.call():

Meteor.call("runCode", myCode, function(err, response) {
  Session.set('code', response);
  console.log(response);
});
Run Code Online (Sandbox Code Playgroud)

但是我runCode在服务器内部的函数Metheor.methods也有一个回调函数,我无法找到一种方法让它response在上面的代码中返回一些内容.

runCode: function(myCode) {
  var command = 'pwd';

  child = exec(command, function(error, stdout, stderr) {
    console.log(stdout.toString());
    console.log(stderr.toString());

    // I Want to return stdout.toString()
    // returning here causes undefined because runCode doesn't actually return
  });

  // I can't really return here because I don't have yet the valuer of stdout.toString();
}
Run Code Online (Sandbox Code Playgroud)

我想办法有exec回调一些回报,因为runCode没有setInterval哪个会的工作,但在我看来哈克的方式.

sai*_*unt 6

你应该使用纤维中的Future.

请参阅此处的文档:https://npmjs.org/package/fibers

从本质上讲,你要做的就是等到运行一些异步代码,然后以程序方式返回它的结果,这正是Future所做的.

你会在这里找到更多:https://www.eventedmind.com/feed/Ww3rQrHJo8FLgK7FF

最后,您可能希望使用此程序包提供的Async实用程序:https://github.com/arunoda/meteor-npm,它会让您更轻松.

// load future from fibers
var Future=Npm.require("fibers/future");
// load exec
var exec=Npm.require("child_process").exec;

Meteor.methods({
    runCode:function(myCode){
        // this method call won't return immediately, it will wait for the
        // asynchronous code to finish, so we call unblock to allow this client
        // to queue other method calls (see Meteor docs)
        this.unblock();
        var future=new Future();
        var command=myCode;
        exec(command,function(error,stdout,stderr){
            if(error){
                console.log(error);
                throw new Meteor.Error(500,command+" failed");
            }
            future.return(stdout.toString());
        });
        return future.wait();
    }
});
Run Code Online (Sandbox Code Playgroud)