JS Callback vs Promises vs Async Await
Difference Between Sync and Async
One important thing to keep in mind is that the single-threaded event handling systems are usually implemented using an event or message queue. So when a program is being executed synchronously, the thread will wait until the first statement is finished to jump to the second one, while in asynchronous execution, even if the first one was not completed, the execution will continue.
Callbacks:
In JavaScript, functions are objects. So we can pass objects to functions as parameters.
We can also pass functions as parameters to other functions and call them inside the outer functions. So callback is a function that is passed to another function. When the first function is done, it will run the second function.
see the example below

If that were sync code, we would have encountered the following output.

But the setTimeout is an async function then the output of the above code will be

In other words, the message function is being called after something happened (after 3 seconds passed for this example), but not before. So the callback is the function that is passed as the argument to setTimeout.
Promises:
A promise in JavaScript is similar to a promise in real life. When we make a promise in real life, it is a guarantee that we are going to do something in the future. Because promises can only be made for the future.
A promise has two possible outcomes: it will either be kept when the time comes, or it won’t.
This is also the same for promises in JavaScript. When we define a promise in JavaScript, it will be resolved when the time comes, or it will get rejected. It sounds like the IF condition. But there are huge differences between them.
A promise is used to handle the asynchronous result of an operation. JavaScript is designed to not wait for an asynchronous block of code to completely execute before other synchronous parts of the code can run. With Promises, we can defer the execution of a code block until an async request is completed. This way, other operations can keep running without interruption.
States of Promises:
First of all, a Promise is an object. There are 3 states of the Promise object:
- Pending: Initial State, before the Promise succeeds or fails.
- Resolved: Completed Promise
- Rejected: Failed Promise, throw an error
Creating a Promise:
Firstly, we use a constructor to create a Promise object. The promise has two parameters, one for success (resolve) and one for fail (reject):

let’s create promise

In the above Promise If Condition is true, resolve the promise returning the “Promise is resolved ”, else return an error “Promise is rejected”. Now we have created our first Promise.
I will continue to write Async wait next time.