1

Have written the Service to fetch the values from the promise and set the values to the Variables in my Service.

Retrives the promise and sets the value to the Variables in Service

 getValueFromPromise =function(){
       myPromise.then(function(res){
         myArray =res;
         console.log("Error");
       });
}                           

This functionality has been coupled to my controller in such a way that it returns array

this.getItems = function(){

       getValueFromPromise(); //Line1
       console.log(myArray); //Line2
       return myArray; //Line3
};

My question actually revolves around getItemsmodule where I invoke a getItemPromise() to set the value to my variable myArray.

  • Question 1: What happens is that in the console I find myArray as [] empty at while loading the UI. Once I refresh my controller, I get the values in the myArray[]. I suspect this because in getItems() promise takes some time in evaluating the .get('URL') and since the operation done in asynchronous manner myArray values gets returned before promise was evaluated.Is that what I suspected right?
  • Question 2: If my Suspection in Question1 was right, How to make Line3 wait till Line1 gets completed.Also Kindly enlighten me if I were anywhere wrong.
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Anandaraja_Srinivasan
  • 568
  • 1
  • 10
  • 25
  • Yes, promises are asynchronous. That's the whole deal. You won't get around that. And no, you cannot block and wait in js. Use callbacks. – Bergi Mar 28 '15 at 14:57
  • Using Callbacks also ends up in same result. Hope it is expected and there is no turn around. :-( – Anandaraja_Srinivasan Mar 28 '15 at 15:38
  • I didn't say that callbacks would block - I mean, you are already using a callback for `then` in the code you posted. The `console.log("Error")` is executed asynchronously fine, and it could as well log the `res` *in that callback*. Or call another callback. – Bergi Mar 28 '15 at 15:47

0 Answers0