Skip to content

Instantly share code, notes, and snippets.

@FikriRNurhidayat
Created September 29, 2019 18:20
Show Gist options
  • Save FikriRNurhidayat/7fd466125fa7ba4f1b71263227c990a2 to your computer and use it in GitHub Desktop.
Save FikriRNurhidayat/7fd466125fa7ba4f1b71263227c990a2 to your computer and use it in GitHub Desktop.
// What is promise actually?
/*
Well promise is just like in real life. It's block of code that will be executed, and return rejection or resolve.
You should handle both of them. Like in real life promise, you can't guarantee it will resolve right?
Wait, what is resolve then? Resolve is fulfilled in real life example.
Let's say, you promise me that you'll always be by my side, so the resolve is, you are always be by my side.
And the rejection is, you leave me.
Great, now I know what the promise is, but how do I handle promise resolve and rejection?
It's simple, there's a lot of ways to execute promise. The one I prever to use is, async await.
So let's jump into it.
*/
// Example of Promise
function standByMe(data) {
return new Promise(function(resolve, reject) {
if (data) return resolve("You're always be by my side.");
reject("You left me.")
})
}
// Execute promise by using .then and .catch
standByMe(true)
.then(data => {
console.log(data);
// It will return You're always be by my side
})
.catch(err => {
console.log(err);
// This line of block won't be executed since the paramater that we pass is true.
})
/*
What does that blocks mean?
.then("This parameter is presenting the resolve of the promise" => {
// And in the .then function, it has callback function which handle the resolve of the Promise.
})
.catch("This parameter is presenting the rejection of the promise" => {
// And in the .catch function, it has callback function which handle the rejection of the Promise.
})
*/
async function executeStandByMe() {
try {
let resolve = await standByMe(true);
console.log(resolve);
}
catch(err) {
let errors = err;
console.log(err)
}
}
/*
By using async function,
basically we just create another promise,
so in case you want to execute it, You can use .then and .catch,
but usually this method being used for event handler.
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment