0

First off, I recently got back into web development after a couple year hiatus. I did a little work with angularjs, but now I switched over to Angular2.

My questions is how do I handle asynchronous js?? I've seen so many demonstrations and articles, but they never seem to apply to my situation. Right now, I am getting information from an API, converting the data into a usable array, and then doing some calculations based on that array (think of it as two functions, one right after the other). How do I handle that, specifically in an angular 2 world?

createArray(){
// Getting data from api (from service)
// Creating an array
// Returning array
}

calculations(){
// Doing calculations on the returned array
}

How do I get calculations to wait for createArray?

qwertybin
  • 55
  • 7
  • 1
    call the `calculations()` only after you get a response from the server. – Vibhesh Kaul Dec 12 '16 at 15:29
  • The articles you've read are most likely applicable. It's up to you to apply what you've learned to the code. –  Dec 12 '16 at 15:38
  • If you're looking for someone to tell you how to simply return the array, it won't happen. We know what you *want* to be able to do, but you just can't do it that simply. –  Dec 12 '16 at 15:41

1 Answers1

0

There are multiple ways of achieving this,

Below uses RxJS,

// Returns an observable
createArray(){
// Getting data from api (from service)
// Creating an array
// Returning array

 // Assuming you are using Angular 2 http service
 return this.http.get('URL', <options>)
    .map(result => {
      // Create Array here using result
      // Call 
    })
}

calculations(someArray){
// Doing calculations on the returned array
}

// Use the methods
someOtherMethod(){
  this.createArray()
      .map(res => this.calculations)
      .subscribe(res => {
        // result after performing calculations on Array from createArray.
      })
}

You may also use Promises for this.

Hope this helps!!

Madhu Ranjan
  • 17,334
  • 7
  • 60
  • 69