Author - StudySection Post Views - 326 views
Javascript

Javascript Callbacks, Promises, and Async/await

In this article, I will cover some tips and tricks for javascript that should be known by all javascript developers.

Callback functions: A callback function is a function passed into another function as an argument, It can run after another function has finished. This technique allows a function to call another function.

Using a javascript callback, you could call the calculator function (myCalculator) with a callback, and let the calculator function run the callback after the calculation is finished.
When you pass a function as an argument, remember not to use parenthesis.
function myDisplayer(some) {
document.getElementById("demo").innerHTML = some;
}
function myCalculator(num1, num2, myCallback) {
let sum = num1 + num2;
myCallback(sum);
}
// Use function without parentheses
myCalculator(5, 5, myDisplayer);

Promise: Promises are used to handle asynchronous/ operations in JavaScript. They are easy to manage when handling multiple asynchronous operations where callbacks can create callback hell resulting in unmanageable code.
A promise is an object that may produce a single value sometime in the future: either a resolved value or a reason that it’s not resolved (e.g., a network error occurred). A promise could also be in one of three possible states: fulfilled, rejected, or pending. Promise users can attach callbacks to handle the fulfilled value or the rationale for rejection.
var promise = new Promise(function(resolve, reject) {
reject('Promise Rejected')
})
promise
.then(function(successMessage) {
console.log(suforccessMessage);
})
.catch(function(errorMessage) {
//error handler function is invoked
console.log(errorMessage);
});

Async/await: An async function is a function declared with the async keyword, and the await keyword is permitted within them. The async and await keywords enable asynchronous, promise-based behavior to be written in a cleaner style, avoiding the need to explicitly configure promise chains.

Example for Async:

async function myFunction() {
return "Hello World!";
}
myFunction().then(
function(value) {myDisplayer(value);},
function(error) {myDisplayer(error);}
);

Await keyword can be only used inside the Async function. It is used before a function makes the function wait for a promise.
async function myDisplay() {
let myPromise = new Promise(function(myResolve, myReject) {
myResolve("I love You !!");
});
document.getElementById("demo").innerHTML = await myPromise;
}
myDisplay();

If you have skills in PHP programming and you want to enhance your career in this field, a PHP certification from StudySection can help you reach your desired goals. Both beginner level and expert level PHP certification exams are offered by StudySection along with other programming certification exams.

Leave a Reply

Your email address will not be published.