Friday, March 16, 2018

Promise in Angular

For asynchronus function call we use call back in Java script. 

Promise API

For asynchronus function call we use Promise. 

The promise constructor takes one function argument. That function, in turn, has two arguments – resolve (we call this if the async operation is successful) and reject (if the async operation fails).

States of a promise

1. Pending
A promise is pending when you start it. It hasn’t been resolved or rejected. It is in a neutral state.

2. Fulfilled
When the operation is successful, a promise is considered fulfilled or resolved.

3. Rejected
If an operation fails, the promise is rejected.

When the promise is no longer in a pending state then…

Exactly… then is the keyword we will use to tell the promise what to do when it succeeds / fails.

The then method has two arguments (functions) which get called based on whether the promise is resolved or rejected. We can pass arguments to these methods through the resolve and reject methods in the Promise constructor.

// To reject promise change value of CONDITION to false
const CONDITION = true;

// Data passed when the promise is resolved
const DATA = 'hello world';

// Error passed when the promise is rejected
const ERROR = new Error('Ooops!');

const promise =
  new Promise((resolve, reject) => {
  // do some async stuff

  if (CONDITION) resolve(DATA);
  else reject(ERROR);
  (data) => { console.log(data); },
  (err) => { console.log(err); }

ES6 adds some more syntactic sugar by allowing you to write the same code like this.

.then((data) => { console.log(data); })
.catch((error) => { console.log(error); });

But All Browsers Don’t Support ES6
You don’t need to worry about that. If you’re working with Angular 2, React, or any other modern framework or library, you’ll be using a transpiler (such as babel with ES6 and tsc with Typescript).

That means that the code will be converted to a readable and usable version for older browsers that don’t support ES6.