What is a Synchronous?
In a synchronous system, tasks are completed one after another.
Think of this as if you have just one hand to accomplish 10 tasks. So, you have to complete one task at a time.
What is an Asynchronous?
In simple terms, Asynchronous tasks are completed independently.
Imagine that for 10 tasks, you have 10 hands. So, each hand can do each task independently and at the same time.
Synchronous example
console.log(" I ");
console.log(" eat ");
console.log(" Ice Cream ");
Asynchronous example
console.log("I");
// In this will be shown after 2 seconds
setTimeout(()=>{
console.log("eat");
},2000)
console.log("Ice Cream")
What are Callbacks?
When you nest a function inside another function as an argument, that's called a callback.
function One(){
let a = 10
let b = 5;
console.log(a + b);
}
function Two(call_One){
console.log("We have added");
call_One()
}
Two(One);
/*
We have added
15
*/
What is Promise?
A promise
is a special JavaScript object. It produces a value after an asynchronous
(aka, async) operation completes successfully, or an error if it does not complete successfully due to time out, network error, and so on.
Successful call completions are indicated by the resolve
function call, and errors are indicated by the reject
function call.
You need to create two files, first index.html
and second index.js
to follow this section.
<!DOCTYPE html>
<html>
<head>
<title>Asynchronous Javascript</title>
</head>
<body>
<script src="index.js"></script>
</body>
</html>
const posts = [
{
name: "Shivam",
body: "This is Shivam"
},
{
name: "Satyam",
body: "This is Satyam"
}
]
function getPosts(){
setTimeout(()=>{
let output = '';
posts.forEach((post, index)=>{
output += `<li>${post.name}</li>`
});
document.body.innerHTML = output;
}, 1000)
}
function createPosts(post){
return new Promise((resolve, reject)=>{
setTimeout(()=>{
posts.push(post)
const error = false;
if(!error){
resolve()
} else{
reject("Something went wrong..");
}
}, 2000)
})
}
createPosts({name: "Sahil", body: "This is Sahil"});
.then(getPosts)
.catch(err => console.log(err))
/*
comment what is output 🤷
*/