0

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) ?

Vincent Gerris
  • 7,228
  • 1
  • 24
  • 22
  • There [may be a more specific Angular version](/search?q=%5Bangular%5D+wait+for+observable) of the [linked question](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call), but the fundamentally, a synchronous function cannot return information that is only available **a**synchronously. It can return a promise for it, or an `Observable`, or some other means of saying "I'll give you the value once I have it," but it can't *return* it. – T.J. Crowder Sep 02 '22 at 09:10

0 Answers0