0

I'm working on getting a json object array using an http get request. Currently, I have a list-view.component that calls a function, getEvents() in my event.service component. That function returns Promise, which represents the object array. It successfully returns the updated array to list-view.component, but for some reason, when I try to print out the array on console, it doesn't show the changes.

list-view.component.ts

this.eventService.getEvents(lat, lon, range, s).then(events => this.eventsList = events);
console.log(this.eventsList);

event.service.ts

getEvents(lat: number, lon: number, radius: number, s: string): Promise<Event[]> {
    return this.http.get(this.eventsUrl + "?s=" + s +"&radius=" + radius + "&lat=" + lat + "&lon=" + lon)
        .toPromise()
        .then(response => response.json() as Event[])
        .catch(this.handleError);
  }

If I try to print the array in the .then method, like below, it prints it correctly.

this.eventService.getEvents(lat, lon, range, s).then(events => console.log(events));

How come, when I try to print it after the this.eventService.getEvents() call, it doesn't have the new changes?

2 Answers 2

1

I'd say thats because the console.logstatement is executed before the promise returns. It works with .then because it`s executed when the promise returns.

Hope this helps.

Sign up to request clarification or add additional context in comments.

Comments

0

Promise.then() is an async method, which means that the value returned can't be used outside of it. Everything you need to do with your events returned by your promise should be put within the .then().

This if for the reason that your method is calling .then(), it will, but the Promise hasn't yet been resolved and the value hasn't yet been set.

Then your method will continue and print your console.log(). Some time (milli/nano-seconds) later, your async operation finished.

You could see it something like this:

fun test() {
   setTimeout(() => {
     console.log('Async operation ended');
    }, 2000);

   console.log('Normal operation ended');
}

which is basically what you created. Your method will call the setTimeout(), and immediately continue with the console.log without waiting for the timeout to finish.

To print the

Async operation ended

Before, you should include it within your setTimeout() (in your case your then())

fun test() {
   setTimeout(() => {
     console.log('Async operation ended');
     console.log('Normal operation ended');
    }, 2000);

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.