javascriptnode.jsasync-awaites6-promisepromise.all

Verify environment using promise.all()


I have to write Node.js script using promise.all() that will check that environment has docker, git, npm, nvm and node.js. For every tool write to stdout the tool version. If some tools doesn't exist write to stderr message about it and finish process with right exit code.

My code is look like this:

const util = require("util");

const exec = util.promisify(require("child_process").exec);

async function getVersion(env) {
  try {
    const { stdout } = await exec(env);
    console.log(stdout);
  } catch (error) {
    console.error(error.stderr);
  }
}

(async function () {
  const fileVersion = [
    "node --version",
    "docker --version",
    "nvm version",
    "git --version",
    "npm --version",
  ];
  const results = await Promise.all(fileVersion);

  for (const element of results) {
    getVersion(element);
  }
})();

I know that in that code promise.all() is not playing any role, I'm not familiar with promise.all() and please anyone could show me an example how to do it?


Solution

  • The Promise.all() method actually takes an iterable of promises as an input (in your code you are just passing an array of strings), and returns a single Promise that resolves to an array of the results of the input promises passed to the function. This returned promise will resolve when all of the passed promises have been resolved (or if the passed iterable contains no promises like in your case). It will also reject immediately upon any of the passed input promises rejecting or non-promises throwing an error, and will reject with this first rejection message / error.

    If you want to actually benefit from the Promise.all() method, you need to pass an array of promises to it instead of the array of strings you're passing right now.

    const util = require("util");
    
    const exec = util.promisify(require("child_process").exec);
    
    async function getVersion(env) {
      try {
        const { stdout } = await exec(env);
        console.log("env is" + stdout);
        return stdout;
      } catch (error) {
        console.error(error.stderr);
      }
    }
    
    (async function () {
      const fileVersion = [
        "node --version",
        "docker --version",
        "nvm version",
        "git --version",
        "npm --version",
      ];
      const results = await Promise.all(fileVersion.map(x => getVersion(x)));
      console.log(results);
    })();