In order to minimize code duplication, I've written some simple JS/TS async functions by encapsulating the respective synchronous function within a Promise. But, not seeing this elsewhere, I'm concerned that I may be missing some design problem(s).
For example:
function fileExistsSync(path: string) {
try {
const result = Deno.statSync(path);
return result.isFile;
} catch (err) {
if (err instanceof Deno.errors.PermissionDenied) {
throw err;
}
return false;
}
}
async function fileExists(path: string) {
return await Promise.resolve().then(() => fileExistsSync(path));
}
async function fileExistsAsync(path: string) {
try {
const result = await Deno.stat(path);
return result.isFile;
} catch (err) {
if (err instanceof Deno.errors.PermissionDenied) {
throw err;
}
return false;
}
}
Is there any observable difference between the functions fileExists() and fileExistsAsync()?
Yes, because fileExists uses Deno.statSync where fileExistsAsync uses Deno.stat.
The sync versions of IO functions block the entire JS execution runtime, while the promise/async Deno.stat version allows other JS code to continue to execute while waiting for a result.