#What is promise ? ####A promise is a special type of Object that we can either use, or construct ourselves to handle asynchronous tasks.A promise has three states, pending, resolved or rejected. ####How to create ES2015 promise
let promise = new Promise((resolved, reject) =>{
if(/*Some asynchronous task*/){
resolved('Sucessfull');
} else {
reject('Something went wrong');
}
});
promise.then(data => {
console.log(data);
});
####We simply call new Promise() and inside can perform an asynchronous task, which may be for wrapping particular DOM events, or even wrapping third-party libraries that are not promise Objects. For example, A third-party library called myCallbackLib() which gives us a success and error callback, we can construct a Promise around this to resolve and reject where appropriate.
const handleThirdPartyCallback = someArgument =>{
let promise = new Promise((resolved, reject) => {
//assuming a third party API that is not a promise but fire a callback after finish
myCallbackLib(someArgument, response => {
//we can resolve it with the response
resolved(response);
}, reason => {
//we can reject it with reason
reject(reason);
});
});
return promise;
};
handleThirdPartyCallback({user: 101}).then(data =>{
console.log(data);
});
##Everything details about promise and $q is in this reference ###Reference: https://toddmotto.com/promises-angular-q#what-is-a-promise