I am having a problem writing clean OOP code, say in TypeScript, while some of my objects contain async methods: what 'ends up' happening is that I am writing static methods, and whichever object or method 'uses' these static methods is 'contaminated' and needs to be converted into a sort of promise itself... I am sure I doing something wrong - is there some architecture trick that I am missing?
Let's take a concrete example: I am writing a Node JS app with a model object of my MongoDB document. Nothing fancy. However, when I use the object's methods in my app, doesn't matter in which class, every method that uses the methods has to be async. And then every method that uses the method that uses the method has to be async as well... etc.
Is there a way to use the MongoDB async operations in such a way as to at least keep up the façade of normal OOP architecture, or is there an entirely new sort of logic I need to learn to write async OOP apps?
Hope I made my question clear,
CodePudding user response:
Async methods don't have to be static, and there really isn't any reason that a program using async operations can't have the same overall structure as one that doesn't.
Async operations are contagious, however. That's known as the red/blue function problem: https://journal.stuffwithstuff.com/2015/02/01/what-color-is-your-function/
It's not ideal, but it's the best that can be done without requiring some very special capabilities from the language/system used to implement JS. You can either have threads, which come with their own problems, or you can have some mechanism for copying call stacks around, like Go and upcoming Java project Loom.