Async Function: Callback, Promises and Await
Async Js is a function in the js that returns the promises and awaits other promises which makes it look synchronous.
First I will talk about callbacks. what are callbacks To explain callback, Here I have made two functions: getPost and createPost.
const posts = [
{title:'post one',body:'This is post one'},
{title:'post two',body:'This is post two'}
];
function getPost(){
setTimeout(() => {
let output='';
posts.forEach((post,index) => {
output += `<li>${post.title}</li>`
});
document.body.innerHTML = output;
},1000);
}
function createPost(post){
setTimeout(() => {
posts.push(post);
},2000);
}
Here this will display the data after 1 sec.
Now createPost will not work because it is taking more time than getpost therefore, if dom is painted first, then you cannot change it again. There we use callbacks and async function.
Now if we use a callback in the createPost, Code will look like this.
function createPost(post,callback){
setTimeout(() => {
posts.push(post);
callback();
},2000);
}
we are using getPost as the callback function. It will wait for 2 seconds and then print all three posts so that they look synchronous.
Now we know the callbacks, let us jump forward to the promises.
function getPost(){
setTimeout(() => {
let output='';
posts.forEach((post,index) => {
output += `<li>${post.title}</li>`
});
document.body.innerHTML = output;
},1000);
}
function createPost(post){
return new Promise((resolve,reject) => {
setTimeout(() => {
posts.push(post);
const error = false;
if(!error){
resolve();
}else{
reject('Error : Something Went wrong');
}
},2000);
});
}
Here using promises, we can return the data but using async js, we can deal with this type of problem more elegantly.
async js code
async function init(){
await createPost({title:'Post Three',body:'This is third post'})
getPost();
} // elegant way of handling the promises
init(); // calling the function
Here await causes the Javascript to pause the code until the promises get executed or fulfill