0

In Angular 11, why does the code following a service call keep on executing even when the service call has not finished?

In Ang11, in a xComponent.ts, I have the following structure:

Why does Line 3 start executing even when the service call has not yet finished fetching & returning the data?

Is this something do with Async calls? How to stop it? With Promise? Sorry, I come from a Java world and learning Angular, and all this is a bit overwhelming for me.

Line 1: <code>
Line 2:  UserDetails ud=this.getUserDetails(userID)
Line 3: <code to work with ud>

Line 99:  getUserDetails(){
          this.userService.getUserDetails(userID).subscribe((data: UserDetails) =>  {
           userDetails:data;
            });
           return userDetails;
         }
Arijit Datta
  • 101
  • 1
  • 2
  • 10
  • getUserDetails doesn't appear to return _anything_. If there are observables involved then yes probably because it's asynchronous. With so little context it's hard to say what exactly the problem is, though. – jonrsharpe Aug 07 '21 at 07:37
  • @jonrsharpe Thanks for your feedback. Have added the context. Hope it helps. – Arijit Datta Aug 07 '21 at 08:05
  • 1
    Returning in the subscribe callback is **not** the same as returning from the actual function (which you don't do). Canonical: https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call – jonrsharpe Aug 07 '21 at 08:23
  • Can you please elaborate? I still dont understand, why Line 3 gets printed first. I did go through the link, but I got lost at the async wait part. – Arijit Datta Aug 07 '21 at 09:40
  • 1
    Remember async calls will return data when it does... its not linear. Actions or functions bound to returned async data, must be processed in that async callback. Many of the issues I have found learning Angular have been timing issues, and its usually depending on data that has yet to be returned. – Darren Street Aug 07 '21 at 11:01
  • @DarrenStreet Absolutely. I have faced it many times! How do I make the control wait, till the method enclosing a service call returns a value / updates a global variable and then my parent method resumes the rest of the processing? – Arijit Datta Aug 07 '21 at 17:49
  • You process the returned data in the callback of the async function. Something like this maybe... yourfuncToGetData.subscribe({ next: (data: typeOfData) => { // do something with the data here eg: console.log(data); }}); – Darren Street Aug 08 '21 at 07:28

0 Answers0