About Async , Await in JavaScript.

Let me explain you ever you here Sync it means execution of any work in Sequential and in linear manner For Example:- When you make tea(chai) firstly we boil water then put ingredients in it like(tea leaves ,masala , milk , Suger) . We wait until first task complete then go to next one . Here if we can apply Sync but their are many tasks in real life & programming like making Rice and Curry that can be managed together So here's come Async
As we know that Java Script is Single Threaded language so If the code Execution is Sync for the long running operations (like network request and the data fetching ) that will take to much of time and Block the rest of the main programme execution So there come async(Asynchronous programming). Which helps us in managing time taking tasks .
The Async Function creates a binding of a new async function to give it name. The await keyword is permitted only inside the async function body enabling asynchronous Promises based Behaviour .
function wait_A_min(){
return new Promise((res,rej)=> // res is for success of the code while
// rej is for something went wrong in / //this code
{setTimeout(()=>{
console.log("Resolved the code .");
res("Code Resolved"); },1000) })
}
async function Example() {
const result=await wait_A_min();
console.log(result);
}
Example();
Await : await is keyword that pauses the code of the Async Function until the promise is settled(resolved or rejected).As you can se in
Example: As we can see Output is in this manner that first Water boiled then all these things will go on this is Happened because of await.
function make_chai() {
return new Promise((res) =>{
setTimeout(() =>{
console.log("Water Boiled");
console.log("Tea leaves added");
console.log("Sugar added");
console.log("Milk added"); res(); }
, 5000); }
);
}
Async function always return a promise. But the promise can be resolved or Can be Rejected.
async function foo()
{ return 1; }
This code is similar to
async function foo(){
return Promise.resolve(1);
}
But their are Some misconception can be created in your mind so i Clear them by adding another code as follows:
const myPromise = new Promise((res) => res("hello"));
const p1 = Promise.resolve(myPromise);
console.log(p1 === myPromise); // true — same object, no wrapping
// Case B — async function returning an existing promise
async function foo() { return myPromise; }
const p2 = foo();
console.log(p2 === myPromise); //false false — brand new Promise object
"So in summary — JavaScript is single-threaded, meaning sync code blocks everything. Async functions combined with await let us write code that reads linearly like sync code, but actually runs non-blocking under the hood. The async keyword wraps your function in a Promise. The await keyword pauses only that function — not the whole programme — until the Promise settles. Together they are the cleanest way to handle time-taking operations like network requests and data fetching in JavaScript."



