Saturday, March 4, 2017

ES6 Promises

To begin with, fetch is an inbuilt method built into the browser and it works like ajax.
fetch() returns a promise, not immediate data.
A promise promises data that is not going to come immediately, but sometime in the future.

The ‘then’ function is a callback. It runs only when data comes back
‘then’ only runs when data successfully comes back
‘catch’ runs when there is an error

const postPromise = fetch(http://stuff);
postPromise //It doesn’t yet know that we expect json data
.then(data=>data.json()) //Converts to json
.then(data=>console.log(data) //prints the actual data
.catch(err=>{console.error(err);})

Manually creating a promise

const prom=new Promise((resolve,reject)=>{
resolve(“i am cool”); //Immediately resolves the promise
});
prom
.then(data=>{console.log(data);})
.catch(err=>console.error(err));
//prints “I am cool”

const prom=new Promise((resolve,reject)=>{
reject(Error(“i ain\’t cool”)); //Immediately rejects the promise
//**Wrap the error message in an ‘Error’ object
//to ensure that the error thrown shows the line no.
}); **/
prom
.then(data=>{console.log(data);})
.catch(err=>console.error(err));

//.all waits for all promises passed to complete
//.all is not on the prototype, it is in the class
Promise
.all([promise1,promise2])
.then(data=>{console.log(data);});


*It is nice to use arrow functions in setTimeout, so that it inherits ‘this’ from the parent element.

No comments:

Post a Comment