In the process of developing a game using Angular, I have implemented the following mechanics:
- An Angular service checks the game state and prompts a necessary user interaction.
- A mediator service creates this prompt and sends it to the relevant Angular component using an RxJS subject.
- The mediator service waits for a response to the prompt before allowing the game to proceed.
- The component captures the user's response to the prompt by calling the
request.respond(response)
method.
To meet these requirements, I needed to design a suitable Request class. Since requests are resolved definitively once initiated, I opted not to use RxJs Observable, choosing instead to utilize JavaScript Promise. Promises can be easily awaited using the async
/await
syntax, and the fourth requirement led me to explore the concept of the Deferred pattern. Consequently, I developed a base class for all types of requests as follows:
abstract class Request<T> {
private _resolve: (value: T) => void = () => {};
private _response: Promise<T> = new Promise<T>(resolve => {
this._resolve = resolve;
});
public get response(): Promise<T> {
return this._response;
}
public respond(response: T) {
this._resolve(response);
}
}
I chose not to include rejection handling since I did not foresee any scenarios in which the request would fail. Even a timeout mechanism seemed unnecessary, given that a response is essential for the game to progress.
While this approach adequately served my needs, I came across discussions labeling it as an anti-pattern (see, for instance, this discussion and this thread). Not being well-versed in working with promises, I am unsure about the potential risks associated with exposing the resolve function, the circumstances under which this pattern could be valid, and alternative methods of achieving my objectives using Promises.
Hence, I am seeking clarification on whether my implementation of the Deferred pattern is appropriate, and if not, what other approaches I could consider to accomplish the desired functionality.