Trying to understand the appropriate way to implement async/await in an async function being called from another function.
public async checkTargetPath(path: string) {
const nixPath = upath.toUnix(path);
let isDir;
let isFile;
const dirTest = await fls.stat(nixPath, (err, stats) => {
if (err) {
throw new Error(`${err.message}`);
} else {
return isDir = stats.isDirectory();
}
});
const fileTest = await fls.lstat(nixPath, (err, stats) => {
if (err) {
throw new Error(`${err.message}`);
} else {
return isFile = stats.isFile();
}
});
if (isDir === true) {
return nixPath;
} else {
return null;
}
}
Which is called from here:
public async copyXmlFromPath(path: string) {
const pathHasTrailingSlash = path.endsWith('/');
if (pathHasTrailingSlash === false) {
path = path + '/';
}
const exec = util.promisify(require('child_process').exec);
const { stdout, stderr } = await exec(`cp ${path}package.xml ./`);
if (stderr !== '') {
throw new Error(`${stderr}`);
} else if (stdout !== '') {
console.log(`package.xml was copied from ${path} to ./`);
}
}
When I step through it, the values of isDir
and isFile
from the first function are always undefined, which I think is because the promises are not resolved.
Can someone point out the failures in the implementation and suggest how to resolve :) ? Links welcome if there are examples that aren't just code blocks!