您可以帮助我了解异步等待如何在Node.js中工作吗?

时间:2020-08-12 18:12:11

标签: javascript node.js asynchronous hubot

我正在尝试为Hubot编写一个脚本,该脚本在远程服务器上运行命令,以获取该服务器上当前安装的各种第三方软件的当前版本。

我的问题是我的getVersions函数即将结束,该函数调用getVersionsOverSSH函数。但是,versions数组在尝试打印版本内容之前不会等待被调用的函数完成。我对Node的经验不是很丰富,所以我对await / async的工作方式的了解有限。有人可以告诉我如何以同步方式运行此脚本,以便在继续运行之前等待SSH函数完成吗?谢谢

getVersions.js

versions = [];

async function getVersions(res) {
  const env = getEnvsFromRequest(res.match[2].toString());
  const resEnv = resolver.resolveEdiEnv(env);
  if (resEnv === null) {
    res.reply(`${env} is not in my list of available environments.`);
    return;
  }
  if (resEnv.length > 0) {
    response = response.concat(`\nHere are the results for ${resEnv}:\n`);
  }
  
  // Resolve hosts for environment
  let resHosts = [];
  resHosts = await resolver.resolveHosts(resEnv);
  // Resolve creds for environment
  let resCreds = [];
  resCreds = await resolver.resolveCreds(resEnv);
  
  try {
    versions = await getVersionsOverSSH(resHosts,resCreds);
    console.log(versions) // this line prints before array is loaded
  } catch (err) {
    console.log(err);
  }
}
// function that makes the ssh calls and appends verions into an array
//  returns array complete with versions from each command

function getVersionsOverSSH(resHosts,resCreds) {
    
  dummy = [];
  const ssh = new SSH({
    host: resHosts[1],
    user: resCreds[0],
    pass: resCreds[1]
  });
  ssh
    // Software 1 version
      .exec('head -3 /app/foo/bar | tail -1 | cut -d \'=\' -f 2', {
        out(stdout) { dummy.push(`Software 1 version: ${stdout}`); },
      })
    // Software 2 version
      .exec('cd /app/foo/foo/bar && ls -td -- * | head -n 1', {
        out(stdout) { dummy.push(`Software 2 version: ${stdout}`); },
      })
    // Software 3 Version
      .exec(`cd /app/foo/bar/foo && ./version.sh | grep Foo* | cut -d \' \' -f 3`, {
        out(stdout) { dummy.push(`Software 3: ${stdout}`); },
      })
      .start();
  
  console.log(dummy); // this prints correctly
  return dummy;
}

1 个答案:

答案 0 :(得分:1)

您需要返回承诺并在需要时解决它。还有execSync在getVersionsOverSSH

function getVersionsOverSSH(resHosts,resCreds) {
  return new Promise((resolve, reject) => {
    dummy = [];
    const ssh = new SSH({
      host: resHosts[1],
      user: resCreds[0],
      pass: resCreds[1]
    });
    ssh
      // Software 1 version
      .execSync('head -3 /app/foo/bar | tail -1 | cut -d \'=\' -f 2', {
        out(stdout) { dummy.push(`Software 1 version: ${stdout}`); },
      })
      // Software 2 version
      .execSync('cd /app/foo/foo/bar && ls -td -- * | head -n 1', {
        out(stdout) { dummy.push(`Software 2 version: ${stdout}`); },
      })
      // Software 3 Version
      .execSync(`cd /app/foo/bar/foo && ./version.sh | grep Foo* | cut -d \' \' -f 3`, {
        out(stdout) { dummy.push(`Software 3: ${stdout}`); },
      })
      .start();
  
      console.log(dummy); // this prints correctly
    //
    resolve(dummy);
  });
}