Return value from a promise in Angular

后端 未结 1 1502
后悔当初
后悔当初 2021-01-18 07:30

I am a little bit confused with Promises. I have the following provider in Ionic + Angular:

@Injectable()
export class StorageProvider { 

  constructor( pub         


        
1条回答
  •  说谎
    说谎 (楼主)
    2021-01-18 07:42

    Logging promise using console.log will just return promise object. StorageProvider's isLogged method should have return true/false so that the underlying caller will receive value inside .then success callback.

    isLogged() {
      return this.retrieve('user').then( value => { 
        //this return will `return` value in chained manner
         return value ? true : false; 
      });
    }
    

    Caller

    this.storage.isLogged().then(
      (value) => console.log("isLogged", value)
    )
    

    Why inner return statement solved the problem?

    Promise is way to deal async request, and it basically has 3 function that can appear in .then.

    myPromiseCall().then(successFn, errorFn, notifyFn)
    

    Sweet properties of promise is they can easily chained up. So that interdependent async code looks more readable. So whenever there is case of passing a data of one promise to another, so that time you returns a data from promiseA success That will automatically available in promiseB success, for eg. below

    promiseA(){return promise };
    promiseB(){ return promise };
    
    promiseA().then( 
       //success fn
       (data) => { 
          //do something
          return data;
       }
    ).then(
       //success fn
       (promiseAData) => {
          console.log("Promise A data", promiseAData);
          //do some awesome thing based on data retrieved from promiseA
    
          return promiseB();
       }
    ).then(successFn, errorFn)
    

    It was important task to return a data from promiseA, that is how when you returned a data, the underlying chained promise success callback function got that data. If suppose the promiseA function didn't returned anything from its success function, the chained promiseB would get undefined. The similar thing was happening with you.

    0 讨论(0)
提交回复
热议问题