For the past few months, I have been immersed in a project that required me to work within a synchronous environment without the need for HTTP requests or other external asynchronous access. However, the scope of the project has now changed, and I find myself needing to fetch data from HTTP requests. Previously, my code looked something like this:
get foo() { return this.value; }
Now, with the introduction of HTTP requests, I must retrieve this value asynchronously and update the variable once the response is received.
fetchValue() { this.http.get(addr).subscribe(resp => this.value = resp); }
get foo() { this.fetchData(); return this.value; }
Unfortunately, this approach doesn't work as intended. Since the event loop only triggers after all logic has executed, this.foo
will always return undefined. Using a while loop is not an option either, as it would prevent the execution of the HTTP request due to its synchronous nature.
Is there a way to pause the synchronous loop and allow the asynchronous operation to complete before proceeding? Or perhaps, can we wait for a specific function in the event loop to finish?
I'm unable to refactor the existing code as it would require a significant overhaul and considerably more time. Moreover, it would break backward compatibility which is crucial for this project. Therefore, I need foo
to return the value only after it has been set; I cannot introduce subscriptions or promise resolutions elsewhere in the codebase to address this issue.
If achieving this is not feasible, could you explain why? I am looking for a clear explanation on the language paradigm that prohibits the implementation of this particular logic.