Meteor callback to sys.exec inside a Meteor.call c

2019-02-23 23:26发布

I have an event triggering a Metor.call():

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

But my runCode function inside the server's Metheor.methods has inside it a callback too and I can't find a way to make it return something to response in the above code.

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

I'd like a way to have the exec callback return something as runCode without setInterval which would work, but as a hacky way in my opinion.

1条回答
Explosion°爆炸
2楼-- · 2019-02-24 00:03

You should use Future from fibers.

See docs here : https://npmjs.org/package/fibers

Essentially, what you want to do is wait until some asynchronous code is run, then return the result of it in a procedural fashion, this is exactly what Future does.

You will find out more here : https://www.eventedmind.com/feed/Ww3rQrHJo8FLgK7FF

Finally, you might want to use the Async utilities provided by this package : https://github.com/arunoda/meteor-npm, it will make your like easier.

// 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();
    }
});
查看更多
登录 后发表回答