
Callback , Async , Await , Promise
Callback, Promises, and Async-await are a way to deal with asynchronous data. Asynchronous programming in JavaScript is a way in which the program doesn’t wait until the execution of something is going on.
In synchronous operations tasks are performed one at a time and only when one is completed, the following is unblocked. In other words, you need to wait for a task to finish to move to the next one.
In asynchronous operations, on the other hand, you can move to another task before the previous one finishes.
A callback is a function that is passed to another function. When the first function is done, it will run the second function.
Example:- function callNames(){ console.log("Sam"); setTimeout(() => { console.log("Sai"); }, 300); console.log("Jai")} callNames();// Sam Sai Jai
2.Async
It simply allows us to write promises based code as if it was synchronous and it checks that we are not breaking the execution thread. It operates asynchronously via the event-loop. Async functions will always return a value. It makes sure that a promise is returned and if it is not returned then JavaScript automatically wraps it in a promise which is resolved with its value.
3.Await
Await function is used to wait for the promise. It could be used within the async block only. It makes the code wait until the promise returns a result. It only makes the async block wait.
Syntax async function name(){ // await statement } Example:- function timing(){ return new Promise(resolve=>{ setTimeout(()=>{ resolve("printing the correct answer") },3000); }) } async function asyncOutput(){ const result=await timing() console.log(result); } asyncOutput();//printing the correct answer
4.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.
A Promise has four states:
fulfilled: Action related to the promise succeeded
rejected: Action related to the promise failed
pending: Promise is still pending i.e. not fulfilled or rejected yet
settled: Promise has fulfilled or rejected
Syntax const promise= new Promise (function(resolve,reject){ //do something }); Example:- const promise=new Promise((resolve,reject)=>{ setTimeout(()=>resolve("resolve means the code will run"),5000) }); promise.then((promise)=>console.log("then means the code is correct",promise)) .catch((promise)=>console.log("catch means the code is incorrect",promise)) .finally(()=>console.log("finally means the code is correct or incorrect return something",)) //then means the code is correct resolve means the code will run finally means the code is correct or incorrect return something.
Let's we see on next Blog...
Thank you...