Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return value from a promise in Angular

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

@Injectable()
export class StorageProvider { 

  constructor( public storage:Storage ) {}

  save(keyname: string, data: any): Promise<any> {
    return this.storage.set(keyname, data);
  }

  retrieve(keyname: string): Promise<any> {
    return this.storage.get(keyname);
  }

  clear(): Promise<void> {
    return this.storage.clear();
  }

  delete(keyname): Promise<any> {
    return this.storage.remove(keyname);
  }

  isLogged() {
      return this.retrieve('user').then( value => { value ? true : false });
  }

}

And in one of my components:

console.log(this.storage.isLogged()); 

The problem is that it returns the promise object and not true or false

If I change my component to:

this.storage.isLogged().then(function(data) { console.log(data)});

Then I get an output of undefined

like image 942
Tasos Avatar asked Aug 12 '17 11:08

Tasos


People also ask

How do I get a value returned from Promise?

It is the fetch() function that returns a value, which is a Promise instance. It is the Promise instance on which you call the then() method, passing in a callback function, which will be eventually be fired when the async code finishes (and internally, calls resolve() ).

How do I return a value from Promise TypeScript?

To access the value of a promise in TypeScript, call the then() method on the promise, e.g. p. then(value => console. log(value)) . The then() method takes a function, which is passed the resolved value as a parameter.

What does a Promise return in angular?

What Is Promise in Angular? Promises in Angular provide an easy way to execute asynchronous functions that use callbacks, while emitting and completing (resolving or rejecting) one value at a time. When using an Angular Promise, you are enabled to emit a single event from the API.

What is then () in angular?

The then() method takes two callback functions as parameters and is invoked when a promise is either resolved or rejected. The catch() method takes one callback function and is invoked when an error occurs.


1 Answers

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.

like image 114
Pankaj Parkar Avatar answered Oct 09 '22 05:10

Pankaj Parkar