Promise is a Javascript object that represents function and its results. Promise helps us handle multiple async function and what will happen after async sunction finish. Promise has 3 main state:
Pending: Initial State
Resolved: After the operation completed successfully.
Rejected: If the operation had error.
Promise provide methods to carry out the result of function: then() and catch().
then(): Kick off when fulfilled or rejected. Often time, people use it when fulfilled.
catch() [optional]: Kick off when rejected.
Async/Await is built on top of Promise, This can be more easier and legible than promise. We can sort async functions like sync functions.
Because this blog is too short, I wanna introduce another concepts in javascript.
Hoisting in javascript is default behavior which moves all the variable and function declarations are moved on top. Remember, just declarations is moved, changing and assign value are not moved. To avoid hoisting, you can run javascript in strict mode by using “use strict”.
Immediately invoked function expressions (IIFE) is a function that is called immediately after defined. Now, we no need to create specified function for simple operation.
var i = 0;
console.log('Before: ', i); // show 0
(function () {
i++;
})();
console.log('After: ', i); // show 1