简体   繁体   中英

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.

My issue is towards the end of my getVersions function, which calls the getVersionsOverSSH function. However, the versions array does not wait for the called function to complete before attempting to print the contents of versions. I am not very experienced in Node, so my understanding of how await/async works is limited. 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? Thank you

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

You need to return promise and resolve it when needed. And execSync inside 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);
  });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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