With node v18, I am trying to loop over an array of directories, and check if that directory is currently on the main
git branch. However the await
doesn’t seem to be doing anything. I often have trouble with promises… what am I missing?
const { promisify } = require('util');
const exec = promisify(require('child_process').exec);
const repos = [
{name: 'repo1'},
{name: 'repo2'},
{name: 'repo3'},
];
repos.forEach(async repo => {
console.log(`...changing dir to ../${repo.name}`);
changeDirectory(`../${repo.name}`)
console.log(`done, current dir is ${process.cwd()}`);
console.log('...checking if on main branch');
const isOnMainBranch = await onMainBranch(); // this `await` isnt doing anything
console.log(isOnMainBranch);
});
async function changeDirectory(path) {
process.chdir(path);
}
async function onMainBranch() {
const output = await exec('git branch --show-current')
const currentBranch = output.stdout.trim();
return currentBranch === 'main';
}
I would expect the output to be:
...changing dir to ../repo1
done, current dir is /var/www/repo1
...checking if on main branch
true
...changing dir to ../repo2
done, current dir is /var/www/repo2
...checking if on main branch
false
...changing dir to ../repo3
done, current dir is /var/www/repo3
...checking if on main branch
true
but what I get is:
...changing dir to ../repo1
done, current dir is /var/www/repo1
...checking if on main branch
...changing dir to ../repo2
done, current dir is /var/www/repo2
...checking if on main branch
...changing dir to ../repo3
done, current dir is /var/www/repo3
...checking if on main branch
true
false
true