There are many questions already asking for how to wait for a promise to resolve. The answer to use await
is pretty obvious now. What's not so clear, however, is how to do that without making the calling function async. Is that even possible?
Background:
In a SymbolTable class I have a function getAllSymbols(): Set<Symbol>
. In a descendant I want to load these symbols dynamically, so I wrote a method loadAllSymbols(): Promise<Symbol>
, which I want to call in the overridden method in my DynamicSymbolTable class:
export class DynamicSymbolTable extends SymbolTable {
public getAllSymbols(): Set<Symbol> {
const existing = super.getAllSymbols();
if (existing.size === 0) {
return await this.loadAllSymbols();
}
return existing;
}
protected loadAllSymbols(): Promise<Set<Symbol>> {
// ... load the content from a remote location
}
}
However, this code requires to make getAllSymbols
to be async and return also a promise. But that changes the signature of the method and it is no longer a valid override of the base class method.
How to implement it so that I can wait for the loaded content without making the calling function (getAllSymbols
) async?
Note: How to return values from async functions using async-await from function? does not answer my question, because it doesn't even touch the important part of it (which is how to avoid async
).