Asynchronous Meteor.call回调中对sys.exec的Meteor回调
我有一个事件触发了一个Asynchronous Meteor.call回调中对sys.exec的Meteor回调,asynchronous,callback,meteor,Asynchronous,Callback,Meteor,我有一个事件触发了一个Metor.call(): 但是我的runCode函数在服务器的Metheor.methods中也有一个回调,我找不到方法让它返回上面代码中的response runCode: function(myCode) { var command = 'pwd'; child = exec(command, function(error, stdout, stderr) { console.log(stdout.toString()); console.l
Metor.call()
:
但是我的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();
}
我想让
exec
回调函数以runCode
的形式返回一些东西,而不使用setInterval
,这是可行的,但在我看来,这是一种黑客方式。您应该使用Future from fibers
请参见此处的文档:
本质上,您要做的是等待某个异步代码运行,然后以过程方式返回结果,这正是Future所做的
您将在此处了解更多信息:
最后,您可能希望使用此包提供的异步实用程序:,这将使您的类似操作更容易
// 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();
}
});
如何在客户端上返回stderr,以便在出现错误时应用程序不会中断?
// 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();
}
});