Basic concepts in the JavaScript programming language
JavaScript programming language is a single threaded language. And it is an interpreted language. Because JavaScript source code does not pass through a compiler before execution. Also, JavaScript usually do not wait for the functions inside executions if it has a delay.
Before jumping to the topic, we need to learn, how to create a function that returns a value after some time.
So, in order to do that, we use setTimeout function.
Now, if you want to set a function has to wait for another function, in order to return a value. What can you do?
So, let’s look at what are the functions called Callbacks, Promises and Asynchronous.
Callbacks
As I mentioned in this screenshot you can create a function called getValue after one second delay. And you can Create a Another function called getNewValue that multiplies a value by 100 after one second delay.
Now using callback (A function as a parameter) you can set getNewValue function has to wait for getValue function.
In the screenshot, you can see when we call the function it is going to be looks like a V shape.
Let’s see what happened if you have to call a lot of functions to use callbacks in the below screenshot.
You can see it is hard to get when we want to find somewhere middle of the code. So, it is called “Callback hell”.
Promises
In this case, you need to return a Promise that includes the setTimeout.
Promise has a function with two parameters. First parameter for success (resolve) scenario and second parameter for failure (reject) scenario. To call a resolve, we can use the “then” keyword. And for a reject, we can use the “catch” keyword.
Using promises is also kind of a long code when we have a lot of functions with promises.
Asynchronous
In this case, you need to create a function with the “async” keyword. After creating the function, you can use the “await” keyword for functions.
Using the Asynchronous function, you can reduce code size when compared with the callbacks and promises.