Are you considering converting an asynchronous
operation to run synchronously?
You might find the solution to a similar issue in this related question Problem returning value from RxJS Observable.
Here's a quick suggestion: try using fromFetch
instead of from(fetch)
Why choose fromFetch
? Because it utilizes the fetch
API internally and completes the observable once the API call is complete.
You seem to be subscribing within the getAssemblyTree
function, which will be invoked after the AJAX request finishes. However, instead of just returning at that point, consider returning the assemblyNodesForTree
variable for better results as the current method will always return empty.
To handle the asynchronous behavior, you can use operators in your observable pipe and perform necessary operations within the map
operator function. Lastly, ensure to return either a Promise
or Observable
from the getAssemblyTree
function.
public getAssemblyTree(id: number) {
....
const request = fromFetch({
url: targetUrl.toString(),
headers: { 'responseType': 'json' }, method: 'GET'
}).pipe(
map(async (response) => {
const assemblyNodesForTree = [];
const data = await response.json()
assemblyNodesForTree.push(
...this.parseAssemblyTree(data['flat_assembly_graph'])
);
return assemblyNodesForTree;
})
);
return request;
}
Example Usage
async myFunction() {
const assemblyNodesForTree = await lastValueFrom(getAssemblyTree(id))
}
Implementing this function is straightforward - simply call the getAssemblyTree(id)
function with lastValueFrom
() wrapper. Upon completion of the fromFetch
API call, the promise will be resolved.