Skip to content

Instantly share code, notes, and snippets.

@tarekahsan709
Last active February 1, 2017 09:21
Show Gist options
  • Save tarekahsan709/ac0b634c6c3c36daebe6043b1fcde8f8 to your computer and use it in GitHub Desktop.
Save tarekahsan709/ac0b634c6c3c36daebe6043b1fcde8f8 to your computer and use it in GitHub Desktop.

#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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment