I am trying to have a function return after an Observable fetches data and no matter what I try it always continues so the return value (that is not the Observable) is undefined. I read many post on the matter and documentation and apparently I am missing something.
I am using Angular/Ionic and Firebase.
I have a conversation function that is a relation between two users on id, I am trying to get the email address from the user, which is the call to the Observable. This is a snippet:
registerConversation(offer: Offer, conversationId?: string): Conversation {
if (!this.conversationExists(offer)) {
const tempIdUser = new User(offer.ownerId,"getuserid@fake.fake");
//this.getConversationForUser(offer,conversationId).subscribe((response:ExtendedUserWithConversations) => {
// console.log("Return in SUBSCRIPT op getCOnvUserFor" + this.returnConversation.id)
// console.log("EN de RESPONSE : " + response.id);
// return this.returnConversation
// } );
this.getConversationForUser(offer,conversationId).then( (result) => {
return this.returnConversation // this happens after where the flow goes
});
//flow seems to always go here - function continues and does not wait for subscribe to finish so returns undefined
} else {
return this.findConversation(offer);
}
}
All I want is for that function to return only AFTER the getConversationForUser is called. I do not understand from documentation or many examples how that call can be made 'synchronous'. I tried tap,map, subscribe and what not.
I would appreciate a really clear explanation and ideally working example. I am not experienced with Angular or Typescript.
I basically fetch a User from Firebase by id and then want to include the email adress from it in the User object that I now make temporarily I try to assign the returned User, use in the conversation setup logic and then return the conversation.
As far as I see it, if the user fetch call can blocking, it should work. Is there any way to achieve this, specifically without making the main function async ( which requires a lot of refactoring) ?