在 Meteor 中延迟将变量从服务器返回到客户端函数 [英] Return variable back from server to client function with delay in Meteor

查看:38
本文介绍了在 Meteor 中延迟将变量从服务器返回到客户端函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I call server function from client, that executes UNIX command and get output on server, but I need to return the result back to client function that called it. I get output on server, but Meteor.call immediately returns the result undefined, bc exec command takes some time to run. Any advice how to delay getting result and bypass this problem?

客户电话:

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 的回调是否被调用,该方法都会在到达函数末尾时返回.这就是异步编程的本质.

This question is being asked about once a week. You can't call return in a callback function. The method will return when it reaches the end of the function, no matter whether the callback of your exec has been called or not. That's the nature of asynchronous programming.

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

You will either need to use a synchronous variant of exec, or return the result to the client in some other way (e.g., a collection that is updated reactively).

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

You can for instance use execSync (https://nodejs.org/api/child_process.html#child_process_child_process_execsync_command_options):

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

这篇关于在 Meteor 中延迟将变量从服务器返回到客户端函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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