【问题标题】:Return variable back from server to client function with delay in Meteor在 Meteor 中延迟将变量从服务器返回到客户端函数
【发布时间】:2015-07-11 10:10:48
【问题描述】:

我从客户端调用服务器函数,它执行 UNIX 命令并在服务器上获取输出,但我需要将结果返回给调用它的客户端函数。我在服务器上得到输出,但 Meteor.call 立即返回结果 undefined,bc exec 命令需要一些时间才能运行。任何建议如何延迟获得结果并绕过这个问题?

客户电话:

if (Meteor.isClient) {
  Template.front.events({
    'click #buttondl': function () {
      if (inputdl.value != '') {
        var link = inputdl.value;
        Meteor.call('information', link, function(error, result) {
          if (error)
            console.log(error);
          else 
            console.log(result);
        });
      }
    }
  });
}

服务器方法:

Meteor.methods({
    information: function (link) {

        exec = Npm.require('child_process').exec;

        runCommand = function (error, stdout, stderr) {
          console.log('stdout: ' + stdout);
          console.log('stderr: ' + stderr);

          if(error !== null) {
            console.log('exec error: ' + error);
          }
          return stdout;
        }

        exec("youtube-dl --get-url " + link, runCommand);
    }
});

【问题讨论】:

    标签: javascript node.js meteor


    【解决方案1】:

    这个问题大约每周被问一次。您不能在回调函数中调用 return。无论您的exec 的回调是否被调用,该方法都会在到达函数末尾时返回。这就是异步编程的本质。

    您要么需要使用exec 的同步变体,要么以其他方式将结果返回给客户端(例如,响应式更新的集合)。

    例如,您可以使用execSync (https://nodejs.org/api/child_process.html#child_process_child_process_execsync_command_options):

        return execSync("youtube-dl --get-url " + link);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-17
      • 2014-01-05
      • 2016-02-14
      • 2016-11-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多