简体   繁体   English

你能帮我理解异步等待在 Node.js 中的工作原理吗?

[英]Can you help me understand how async await works in Node.js?

I am trying to write a script in Node for hubot that runs commands on a remote server to get the current versions of various third party software currently installed on that server.我正在尝试在 Node 中为 hubot 编写一个脚本,该脚本在远程服务器上运行命令以获取当前安装在该服务器上的各种第三方软件的当前版本。

My issue is towards the end of my getVersions function, which calls the getVersionsOverSSH function.我的问题是在我的 getVersions function 快结束时,它调用 getVersionsOverSSH function。 However, the versions array does not wait for the called function to complete before attempting to print the contents of versions.但是,版本数组在尝试打印版本内容之前不会等待被调用的 function 完成。 I am not very experienced in Node, so my understanding of how await/async works is limited.我在 Node 方面不是很有经验,所以我对 await/async 工作原理的理解是有限的。 Can someone tell me how to run this script in a synchronous manner, so that it waits for the SSH function to complete before moving on?有人可以告诉我如何以同步方式运行此脚本,以便在继续之前等待 SSH function 完成吗? Thank you谢谢

getVersions.js获取版本.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;
}

You need to return promise and resolve it when needed.您需要返回 promise 并在需要时解决。 And execSync inside getVersionsOverSSH和 getVersionsOverSSH 里面execSync

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);
  });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM