在Meteor中延迟从服务器返回变量到客户端函数

Return variable back from server to client function with delay in Meteor

本文关键字:变量 客户端 函数 返回 服务器 Meteor 延迟      更新时间:2023-09-26

我从客户端调用服务器函数,它执行UNIX命令并在服务器上获得输出,但我需要将结果返回给调用它的客户端函数。我在服务器上得到输出,但是流星。调用立即返回结果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);
    }
});

这个问题每周被问到一次。你不能在回调函数中调用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);