Promise me you will Callback
10 March, 2021 - 3 min read
Callback
First thing first, what is a callback or a callback function? So we know a function is a block of codes which we write to perform a certain thing (i.e. to remove an item or to add an item) and we want to reuse it later. A callback function is a function which is passed into another function as an argument and is supposed to be called back. So simply put, you call a function A, which will after finishing its job then call a function B. B in this case is the callback function. In asynchronous operation, callback is really helpful because it needs to wait for another function to work before it can run. For example when we open an url / a link / a page and we want to do something with the content of the page after the page is loaded, successfully or not.
Promise
A promise is a JavaScript object, which works pretty much like a promise in real life. A promise in real life is a guaranteed action to be done in the future. A promise can be kept or not. So is a promise in JavaScript. A promise can be:
- Pending (the result is undefined, the process is working)
- Fulfilled (the result is resolved/successful and return a value)
- Rejected (the result is rejected due to an error)
We simply create a promise by creating a promise instance with keyword “new”:
let myPromise = new Promise(function(Resolve, Reject) {
let weather = “ ”; // condition
if (weather == “sunny”) {
Resolve("Let’s go to the beach");
} else {
Reject("Errr, too cold to go");
}
});
Resolve() and Reject() are the callback functions which we pass onto the Promise function to do the action based on the result returned by the promise.
After that we can use promise by chaining the “.then()” to display the result value of a fulfilled promised and/or “.catch()” to display an error object
myPromise.then(
function(result) {
console.log(result); // will print "Let’s go to the beach"
}).catch(error) {
console.log(error); // will print "Errr, too cold to go"
});
Async / Await
So now we understand the concept of callback and promise, we can tackle async and await. Async and await just simplify all these for you in a very nice way. Basically these are just keywords or constructors like “new” to define the scope of the function. While async declares a function to return a Promise even though we dont write a promise ourselves, await declares a function to wait for a promise to resolve. We put them both before the function we define like this: