【问题标题】:Promise chaining + return variable with meteor callbackPromise 链接 + 带有流星回调的返回变量
【发布时间】:2017-06-22 22:01:58
【问题描述】:

如何实现以下目标?

服务器端:

执行 bash 命令生成文件。然后返回文件D的路径

const exec = Meteor.isServer ? require('child_process').exec : undefined;

Meteor.methods({
  createFile_D(){
    const BashCommand_A = `generate file A`;
    const BashCommand_B = `generate file B, using file A`;
    const BashCommand_C = `generate file C, using file B`;
    const BashCommand_D = `generate file D, using file C`;

    const runCommand = function (cmd) {
      let command = exec(cmd, path);
      command.stdout.on('data', (data) => {
        console.log(`stdout: ${data}`);
      });
      command.stderr.on('data', (data) => {
        console.log(`stderr: ${data}`);
      });
      command.on('close', (code) => {
        console.log(`child process exited with code ${code}`);
        resolve('done');
      })
    }

    // execute BashCommand A ~ D
    // when it's all done return the path of file D

  } 
});

客户端:

获取生成文件 D 的路径作为 Meteor.call 的回调

Meteor.call('createFile_D', function (error, result) {
  if(error || (result === undefined)) {
    throw error;
  } else {
    do_something_with_result (result);
  }
});

【问题讨论】:

  • runCommand 是如何/在哪里执行的?
  • 我可以让你走这么远in this fiddle 不幸的是,我对 Meteor 的了解还不够,不知道现在该做什么:p

标签: javascript meteor promise


【解决方案1】:

使用Meteor.wrapAsync 或异步/等待:

const runCommand = (cmd) => {
  return new Promise((resolve, reject) => {
    // Make sure `path` variable is exists
    let command = exec(cmd, path);
    command.stdout.on('data', (data) => {
      console.log(`stdout: ${data}`);
    });
    command.stderr.on('data', (data) => {
      console.log(`stderr: ${data}`);
    });
    command.on('close', (code) => {
      console.log(`child process exited with code ${code}`);
      resolve(path);
    })
  });
};

Meteor.methods({
  async createFile_D(){
    const BashCommand_A = `generate file A`;
    const BashCommand_B = `generate file B, using file A`;
    const BashCommand_C = `generate file C, using file B`;
    const BashCommand_D = `generate file D, using file C`;


    await runCommand(BashCommand_A);
    await runCommand(BashCommand_B);
    await runCommand(BashCommand_C);
    const path_D = await runCommand(BashCommand_D);

    // path_D from resolve() in Promise
    return path_D;
  } 
});

阅读更多关于等待/异步的信息

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-03
    • 1970-01-01
    • 2023-04-03
    • 2018-09-16
    相关资源
    最近更新 更多