Asynchronous JavaScript — Callbacks & Promises

Mihara Inuri
3 min readFeb 20, 2022

~This is my very first attempt on Medium. So let’s get started…

JavaScript is a single threaded language which means it has a single call stack and a single memory heap. i.e. it runs a single thing at a time.

WHAT IS ASYNCHRONOUS JS?

Asynchronous JavaScript allows you to move to another task before the previous task finishes. Simply, asynchronous functions run parallelly with other functions.

setTimeout() method is a good example for Asynchronous JavaScript.

<script>        function getValue(){
let value=0;

setTimeout(function(){
value = 10;
},1000);
return value;
}
console.log(getValue());

</script>

Output of the above code snippet is Zero. Because it won’t wait until inner function(setTimeout()) executes.

There are mainly 3 types of asynchronous code styles in JavaScript; They are callbacks, promises, and async/await.

Here we are going to get to know about callbacks and promises…

1.Callback Function

Callback is a function that is used to passed into another function as an argument. It does not rely on environment bound variables.

We can use the callback function to execute the inner function of the above code snippet as follows.

<script>
function getValue(callback){
let value = 0;

setTimeout(function(){
value = 10;
callback(value);
},1000);
return value;
}

getValue(function(value){
console.log(value);
});
</script>

Output of the above code snippet is 10.

Callback Hell??🧐🤔

Nested callbacks passed into sequence of asynchronous tasks is referred to a callback hell. Callback Hell is also known as “Pyramid of Doom”.

Nesting callbacks may lead to a code which is error-prone, complex and difficult to handle.

💡: Promises help to get rid of callback hell…

2.Promise Function

Promise lets asynchronous methods to return values like synchronous methods.

Promise is an object which has a set of properties, methods and mechanism of chaining to handle complex asynchronous tasks

Basically, there are 3 states where a promise can be stated. They are,

i) Pending: Initial state of the promise

ii) Fulfilled/Resolved: Particular operation is successfully completed

iii) Rejected: Operation failed

Note: Some depicts 4 promise states where an additional state called ‘settled’ is introduced. Settled means the promise has fulfilled or rejected.

Below code snippet will tell you how to use promise function.

<script>
let promise = new Promise((resolve, reject)=>{
resolve();
reject();
});

function getValue(){
let value = 0;
return new Promise((resolve, reject)=>{
setTimeout(function(){
value = 10;
resolve(value);
},1000);
});
}

getValue().then(function(value){
console.log(value);
});


</script>

Output of the above code snippet is 10.

Conclusion

We learned a bit of Asynchronous JavaScript and some of its concepts.

That’s it for now, and please press the clap button if you find this article helpful.

--

--