Javascript Essentials

Sailee Renapurkar
4 min readMay 29, 2021

--

When I started working on Javascript, I often used to get confused with callbacks, asynchronous functions, promises, async/await. These were the concepts that were almost used every day while development. Over time, I have understood the difference and thought of explaining those concepts in a very simple and easy-to-understand way for people who are new to this. This blog is about the basic understanding of these concepts and will help you dive deeper into them further.

Javascript Callbacks:

A callback is a function passed as an argument to another function. This technique allows a function to call another function. A callback function can run after another function has finished.

In Javascript, functions are executed in the sequence in which they are called and not in the sequence they are defined. Let me explain this with an example

e.g

function sayHi() {
display(“Hi”);
}
function sayBye() {
display(“Goodbye”);
}
sayBye();
sayHi();

This will end up displaying “Bye” and then“Hi”.

Sometimes we would like to have control over function as to when to execute it.

Consider a scenario where you want to display the file contents after the file has completely been loaded. Then this is the time to use a callback. As mentioned earlier, the callback is a function passed as an argument to another function.

Callbacks make sure that a function is not going to run before a task is completed but will run right after the task has been completed.

Let’s understand this with a simple example:

const message = function() {
console.log(“This message is displayed after 3 seconds”);
}
setTimeout(message, 3000);

the message function is being called after something happened (after 3 seconds passed for this example), but not before. So the message function is an example of a callback function.

Using a callback, you could call the calculator function with a callback, and let the calculator function run the callback after the calculation is finished

Remember, when you pass a function as an argument you don’t use the parenthesis.

Asynchronous Javascript:

The functions which do not block the execution thread are called asynchronous functions.

e.g Javascript setTimeOut()

function display(result) {document.getElementById(“demo”).innerHTML = result;}function getFile(myCallback) {let request = new XMLHttpRequest();request.open(‘GET’, “car.html”);request.onload = function() {if (request.status == 200) {myCallback(this.responseText);} else {myCallback(“Error: “ + request.status);}}request.send();}getFile(display);

In the example above, a display is used as a callback.
Instead of passing the function reference as an argument, we can pass the whole function itself.

setTimeout(function() { document.getElementById(“demo”).innerHTML = “Fun”; }, 1000);

Javascript Promises:

Producing code is code that can take some time
Consuming code is code that must wait for the result

A Promise is a JavaScript object that links producing code and consuming code or we can say that A promise is an object that may produce a single value some time in the future: either a resolved value or a reason that it’s not resolved (e.g., a network error occurred).

Promise Syntax:

let promise = new Promise(function(resolve, reject) {// producing code (can take some time)resolve(result value); // when successfulreject(error object); // when error});// consuming code (must wait for fulfilled promise)myPromise.then(function(value) {//todo when successful},function(error) {//todo when failure });

When the producing code obtains some results it should be one of the following callbacks based on the result.

  1. Success -> resolve(result value)
  2. Error -> reject (error object)

Promises allow us to associate actions to be executed after the eventually obtained success value or failure value.

A Promise is in one of these states:

  • pending: initial state, neither fulfilled nor rejected.
  • fulfilled: meaning that the operation was completed successfully.
  • rejected: meaning that the operation failed.
function display(result) {
document.getElementById(“demo”).innerHTML = result;
}
let loadFile = new Promise(function(resolve, reject) {
let request = new XMLHttpRequest();
request.open(‘GET’, “flower.html”);
request.onload = function() {
if (request.status == 200) {
resolve(request.response);
}else{
reject(“File not Found”);
}};
request.send();
});
loadFile.then(
function(value) {display(value);},
function(error) {display(error);}
);

Javascript Async:

async makes a function return a Promise.
await makes a function wait for a Promise.

Async syntax:

The keyword async before a function makes the function return a promise:

async function myFunction() {
return Promise.resolve(“Hello”);
}

Await syntax:

The keyword await before a function makes the function wait for a promise

let value = await promise.

The await keyword can only be used inside an async function.

E.g

async function getFile() {
let myPromise = new Promise(function(myResolve, myReject) {
let req = new XMLHttpRequest();
req.open(‘GET’, “mycar.html”);
req.onload = function() {
if (req.status == 200) {myResolve(req.response);}
else {myResolve(“File not Found”);}
};
req.send();
});
document.getElementById(“demo”).innerHTML = await myPromise;
}

--

--