JavaScript Callback, Promises and Async

Hirush Gimhan
4 min readMar 3, 2021

Why we need these methods?

JavaScript has two main programming concepts

  • Synchronous Programming
  • Asynchronous Programming

Let’s look at more in-details.

1. Synchronous Programming

  • JavaScript one thing is happening at a time. That’s mean JavaScript is Single threaded programming language.
  • When we execute the code, one line of code is being executed at time in order of the code appears.
  • In this case, it will wait for each statement to complete its execution before going to the next code statement.

2. Asynchronous Programming

  • In this case, it will NOT wait for each statement to complete its execution before going to the next code statement.
  • So with Asynchronous JavaScript, the JavaScript doesn’t wait for responses when executing a function, instead it continues with executing other functions. So then why we need to know Callback, Promises and Async.

CALLBACKS

//[1] create array object and assign some values
const persons = [
{name: 'John'},
{name: 'Anne'},
{name: 'Marcus'}
];

//[2] display the person names
function getNames() {
setTimeout(() => {
let personNames = '';
persons.forEach((persons, index) => {
//personNames += `"${persons.name}"`+` `;
personNames = personNames + (`"${persons.name}"` + ` `);
});
console.log(personNames);
}, 1000);
};

In this code segment, I am trying to explain Callback behavior.

The code is going to display person names which contain persons[1] array object and setTimeout() method is used to more illustrate Asynchronous behavior.

So here, we add another function called enterPersonName().

//Add new person to the array object
function enterNewPerson(person) {
setTimeout(() => {
persons.push(person);
}, 2000);

};

This is the Scenario

I want add new person into persons[1] array object and display it console. (persons.push() method used to add new value into persons array object).

Pretty easy right?

Note: look at the setTimeout milliseconds! getNames() contain 1000 milliseconds and enterNewPerson() contain 2000 milliseconds. Did you notice that?

Here is the output

  • Actual output — “John” “Anne” “Marcus”
  • Expected output — “John” “Anne” “Marcus” “Juli”

Did we get the Expected output? No! right?

Why is that happened?

As I told before JavaScript is Synchronous and Single threaded programming language. So the execution of enterNewPerson() method has 2 second timeout and in the meantime the getNames() method completes its execution.

So then, how can we get the Expected output?

Here’s the code

// //callback function implementation
// //[3]
function enterNewPerson(person, callback) {
setTimeout(() => {
persons.push(person);
//[4]
callback();
}, 2000);
};
enterNewPerson({name: 'Juli'}, getNames);

We should use Callback method to get our expected output.

In this above code, what I did was, we need pass new parameter to enternewPerson() method. That parameter is callback[3].

After that we should call the callback method inside the setTimeout() method.

Are you confused? No right? If yes, here’s the simple logic.

Let’s look at the method called.

enterNewPerson({name: 'Juli'}, getNames);

There is a two parameter. First parameter is our new person name and Second parameter is our display method name which is getNames() method. So after the pass that two parameters, callback method is hold the getNames() method until new person added to persons[1] array object. After the new person added to the array object, we can call the callback()[4] method. That method call to the getNames() display method.

You think now “Is there any easiest way to do this? I little bit confused!”

Why did you think like this?

Because there are nested functions, and some method pass to another method parameter like so many things you may think. Isn’t it guys?

Don’t worry! We have two ways to do this. So stay calm and focus!

PROMIESES

In this Phrase, we don’t need to pass any callback function. But promises has two parameters resolve and reject. Special thing is if function executes successfully, we can call resolve() method. If not, we can call reject().

Here’s the code

// Promise function implementation
function enterNewPerson(person) {
return new Promise((resolve, reject) => {
persons.push(person);
let isSuccess = true;
if (isSuccess) {
resolve();
} else {
reject('Something went wrong!');
}
});
};
enterNewPerson({name: 'Juli'}).then(getNames).catch(onerror => console.log(onerror));

Okay! Okay! I know… You argue with me CALLBACK function is very short, PROMISES has several statements. Actually there is no any hard things. Only has simple if else statement.

But code is clear right? So let’s look at the enterNewPerson() method called.

enterNewPerson({name: 'Juli'}).then(getNames).catch(onerror => console.log(onerror));

When the code call, we should call then() method to execute the code. And other special thing is we can catch whenever some problem rises inside the code and print in the console log.

.catch(onerror => console.log(onerror));

Okay! Are we clear up to this point? So then move to the last part in our Blog.

ASYNC and AWAIT

Trust me! This is the easiest way to handle Asynchronous situation.

Less code! More understandable!

Here’s the code

function enterNewPerson(person){
persons.push(person);
}
// Async and Await implementation
async function useOfAsyncFunction() {
await enterNewPerson({name: 'Juli'});
getNames();
};
useOfAsyncFunction();

See? enternewPerson() method pretty understand right? Very simple function.

So when we call the function, we need to create new function. useOfAsyncfunction() method is the new function and this method inside the our enterNewPerson() method. And after that we call print method which is getNames(). Pretty easy right?

Special thing is here, carefully look at the function!

Before the function keyword we should provide async keyword. And also Before the enterNewPerson() method we should provide await keyword.

Finally, we need to call new create method which is useOfAsyncfunction(). That’s all. That’s the beauty of async and await concept.

So we will meet soon another blog! #Goodluck! #HappyCoding! #Thankyou!

--

--

Hirush Gimhan

SLIIT- Undergraduate(Software Engineer) | Graphic Designer | Coder | Positive Mind | Creative Mind | Helper