Node.js-Await不等待该方法先执行

时间:2019-04-26 01:32:50

标签: node.js async-await

我正在用nodejs编写一个函数,以将打印命令发送到macOS。问题是我的打印命令已成功发送,但是我想等待接收到的输出再继续前进。

我的代码如下

const printer = require("node-native-printer");
const exec = require("child_process").exec;
module.exports = {
  print: async function (options) {
    await this.printUnix(options).then(
      response => {
        return response
      }
    ).catch(error => {
      return false
    });
  },

  printUnix: async function (options) {
    if (!options.filePath)
      return Error('File path not specified');
    let command = 'lp ';
    let unixOptions = [];
    await Object.keys(options).forEach(value => {
      switch (value) {
        case 'duplex':
          if (options[value] === 'Default')
            command = command + '-o sides=one-sided ';
          else
            command = command + '-o sides=two-sided-short-edge ';
          break;

        case 'color':
          if (options[value])
            command = command + '-o blackplot ';
          break;

        case 'landscape':
          if (options[value])
            command = command + '-o orientation-requested=4 ';
          else command = command + '-o orientation-requested=3 ';
          break;
      }
    });
    command = command + options.filePath;

    return await this.executeQuery(command);
  },

  executeQuery: async function (command) {
    exec(command, function (error, stdout, stderr) {
      output = {stdout, error, stderr};
      if (!stdout || stderr || error)
        return false;
      else
        return true;
    });
  }
};

这里的问题是函数executeQuery没有完全执行,并且返回了结果,即未定义。如何让我的程序等待功能正常执行?

2 个答案:

答案 0 :(得分:1)

executeQuery无法按预期工作,因为您将Async-Await与回调混合使用。

您不能将Async-await语法与回调一起使用。您必须按照下面的说明使用回调函数。

    function(command){
        return new Promise(resolve, reject){
             exec(command, function (error, stdout, stderr) {
             output = {stdout, error, stderr};
             if (!stdout || stderr || error)
                 reject();
             else
                 resolve();
             })
        }
    }

答案 1 :(得分:0)

好的,看来这是错误的

   await this.printUnix(options).then(
      response => {
        return response
      }
    ).catch(error => {
      return false
    });
  },

使用异步/等待时。您不能使用承诺回调.then.catch(可能)

尝试将代码更改为类似

 print: async function (options) {
   try {
     return await this.printUnix(options)
     } catch (error) {
      return false
  },