流星回调到Meteor.call回调里面sys.exec [英] Meteor callback to sys.exec inside a Meteor.call callback

查看:149
本文介绍了流星回调到Meteor.call回调里面sys.exec的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

但是这里面我运行code 功能服务器的 Metheor.methods 有所回调里面也和我不能找到一种方法,使其恢复一些在上code 响应

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

我想办法有 EXEC 回调一些回报为运行code 的setInterval 这会的工作,但在我看来哈克的方式。

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.

推荐答案

您应该从纤维使用未来。

You should use Future from fibers.

请参阅文档在这里: https://npmjs.org/package/fibers

从本质上讲,你想要做的是等待,直到某个异步code运行时,则返回它的结果在一个程序的方式,这是未来做什么。

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.

您会发现更多在这里: https://www.eventedmind.com/feed/Ww3rQrHJo8FLgK7FF

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

最后,您可能希望使用此包中提供的异步工具: https://github.com / arunoda /流星NPM ,它会让你更容易喜欢

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

这篇关于流星回调到Meteor.call回调里面sys.exec的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆