1

根据文档require('child_process').exec,您可以通过执行以下操作来承诺 NodeJS' :

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

async function lsExample() {
  const { stdout, stderr } = await exec('ls');
  console.log('stdout:', stdout);
  console.error('stderr:', stderr);
}
lsExample();

但是,当我在 'prepare-commit-msg' git 挂钩中使用这种方法来获取当前分支名称时,stdout常量是一个承诺对象,而不是我期望的分支名称值。我错过了什么吗?

const util = require('util');
const stdExec = require('child_process').exec;
const exec = util.promisify(stdExec);

async function getBranchName() {
  const { err, stdout, stderr } = await exec('git rev-parse --abbrev-ref HEAD');

  console.log(err, stdout, stderr); // Returns correct stdout

  if (err) {
    // "git branch" will fail if initial commit hasn't been done, in that case, skip this hook
    process.exit(0);
  }

  return stdout;
}

function validateBranchName(name) {
    console.log(name);
)

// Call get branchName
if(condition) {
    const branchName = getBranchName(); // branchName is promise object

    validateBranchName(branchName);
}
4

1 回答 1

0

我通过将函数被调用到另一个异步函数的位置来解决这个问题:

const util = require('util');
const stdExec = require('child_process').exec;
const exec = util.promisify(stdExec);

async function getBranchName() {
  const { err, stdout, stderr } = await exec('git rev-parse --abbrev-ref HEAD');

  console.log(err, stdout, stderr);

  if (err) {
    // "git branch" will fail if initial commit hasn't been done, in that case, skip this hook
    process.exit(0);
  }

  return stdout;
}

function validateBranchName(name) {
    console.log(name);
)

function async prepareCommitMsg() {
    const branchName = await getBranchName();

    validateBranchName(branchName);
}

// Call get branchName
if(condition) {
    prepareCommitMsg().then(() => {console.log('DONE!')});
}
于 2020-05-13T13:35:47.463 回答