Javascript callback promise await/async

I have been coding in JavaScript for a while now, but I realized that I didn’t have a solid understanding of how the language works. This was a surprising realization, considering how much time I spend working with it. So, to improve my skills, I decided to do some research and dive deeper into the workings of JavaScript.

JavaScript is a programming language designed to run on client-side browsers. In this context, everything related to the internet is unpredictable. For example, if an image is too large, the browser can get stuck, and that’s where callback functions come in.

A callback function is a function that’s passed as an argument to another function. It’s used to execute code asynchronously, which means that the program doesn’t stop until the function is executed entirely. The concept of a callback is that we put the functions that need time to run into a “Callback Queue” and continue running the following code. This allows us to avoid blocking the program while it waits for the function to finish running.

Another useful feature of JavaScript is the Promise object. A promise is an object that includes a resolve and reject function. The resolve function is called when the code runs successfully, while the reject function is called when the code throws an error. We use try-catch blocks to handle errors in promises.

Async/Await is another feature of JavaScript that’s used for clean code. The await keyword is used in the async function to pause the function until the Promise is resolved or rejected. We can use this feature to write asynchronous code that looks like synchronous code, which makes the code easier to read and understand.

In summary, JavaScript is a powerful language that’s essential for web development. Understanding its features, including callback functions, Promises, and Async/Await, is crucial for writing efficient and clean code.

Callback

The concept of callback is that, we put the functions that needs time to run into a “Callback Queue”, and continue run the following code.

Promise

Promise is object that include resolve and reject, for example,

1
2
3
4
5
6
7
8
9
10
11
12
13
let p = new Promise(function(resolve, reject) {
if(){
resolve();
}else{
reject;
}
})

p.then(function(){
// resolve
}).catch(function() {
// return a exception, and catch the error
})

Async Await

The await must be in the async function

1
2
3
4
5
6
7
8
9
async function getSomething(){
try{
let something = await fetch(url);
console.log(something)
}
catch( exception ){
console.log(exception)
}
}

Async await is usually the better for clean code.