In my business logic library, there is a method designed to run asynchronously that takes false as an argument in an if statement. When executed asynchronously, everything works fine:
const permissions = new PermissionProvider(userId, appId);
if(await permissions.ifAllowed('invalid action', itemID)){
// This code will not be reached.
}
export class PermissionProvider {
...
public async ifAllowed(action: string, itemId?: string): Promise<boolean> {
return await db.query(params)
.then(() => { return false; }
}
However, I am worried that someone might unintentionally execute the code synchronously:
if(permissions.ifAllowed('invalid action', itemID)){
// This code runs because asynchronous functions return a Promise,
// and objects evaluate to true.
}
Simply relying on documentation instructing the API to be used with async/await seems risky. It could lead to unexpected consequences since it may not be immediately apparent to the end user that omitting the await keyword gives them virtually unrestricted access.
If I were to return a primitive boolean instead, the async code would then return undefined since it originates from the database as a Promise.
Is there a satisfactory solution to either enforcing asynchronous calls by the API consumer or preventing the if statement from evaluating to true?
I attempted to throw an uncaught error, but it still executes the code because the error is thrown after the if statement has already been evaluated.