1

Hi I am rather new to Javascript. Recently I encountered an issue whereby my code is not executing synchronously. The followings are my implementation:

// Step 1
// method call to submit data retrieve from service call
submit() {
   if(this.checkPrice()){
     // submit data to backend
    }else {
     // trigger ANOTHERMETHOD()
    }
  }

// Step 2
// check if price is able $2 
checkPrice(){
    const result = this.dataRetrieveFromAPI();
       if(result !== undefined && result > 2) {
          return true;
       }else {
          return false
       }
    }


// Step 3
// method to retrieve data from API
dataRetrieveFromAPI(){
   this.httpservice.getData().subscribe(x=>{
       if(x){
   // manipulate x data
       var a = x.price;
      return a
       }
  });

I notice that at Step 2, my result will always be undefined as the API call to step 3 from step 2 will not wait till result is return from step 3. As such, I would like to seek some advice on how should I modify this to become a synchronous call?

  • 1
    There are many tricks to help make working with asynchronous code easier to understand, from callbacks, to Promises, to async-await. But nothing is going to make asynchronous code synchronous. If `dataRetrieveFromAPI` is asynchronous, the code surrounding it will need to be so too. – Scott Sauyet Jul 24 '20 at 15:17
  • 2
    ^^ I don't think it's been said better than the above by @ScottSauyet. But well done: You were bang-on correct about what the problem was. A lot of people wouldn't have been. – T.J. Crowder Jul 24 '20 at 15:19

0 Answers0