Asynchronous Programming

Q1. What is Asynchronous in Javascript?
Ans:- Asynchronous means, when one task is executing, you can switch to a different task without waiting for the previous task to be completed.
Q2. What is synchronous in javascript?
Ans:- Synchronous means, tasks are executed one after another. each task waits for the previous task to be completed.

Q3. What is a single thread in js?
Ans:- A single-threaded language means it has only one call stack that is used to execute the program. and in a single thread, we can do only one work at one time. and JavaScript is a single-threaded language.
Q4. What is multiple-threaded?
Ans:- Multiple-threaded means it has multiple call stacks and we can do multiple works at the same time.
How to Handle async task:-
Q1. What is Callback?

Ans:- Callback is a function that is passed into another function as an argument. callback function runs after another function has finished.
// function
function greet(name, callback) {
console.log('Hi' + ' ' + name);
callback();
}
// callback function
function callMe() {
console.log('I am callback function');
}
// passing function as an argument
greet('Peter', callMe);
Q2. Why do we use callbacks?
Ans:- we need the callback function because many javascript operations are asynchronous, which means they don't stop functions until they are completed.
Q3. What is callback hell in javascript?
Ans:- Callback hell is an anti-pattern of nested callback, which makes code hard to read and debug when dealing with async logic.
const animateAll = (animate) => {
setTimeout(() => {
animate(words[0]);
setTimeout(() => {
animate(words[1]);
setTimeout(() => {
animate(words[2]);
}, 1000)
}, 1000)
}, 1000)
}
How to avoid a callback hell?
Ans:- with the help of Promise, we can easily avoid callback hell.
Why do we use Promise instead of callbacks?
Ans:- Promise are handle multiple asynchronous tasks easily at the same time and in the promise we can easily handle errors.
Q. What is Promise and what overview of Promise?

Ans:- Promise:- Promise is a Javascript object, that is used to handle the asynchronous task.
The Promise object has two properties:- state and result
Three states of Promise:-
- Pending state:- While a Promise object is "pending" (working), the result is undefined.
- Fulfilled state:- When a Promise object is "fulfilled", the result is a value.
- Rejected state:- When a Promise object is "rejected", the result is an error object.
const promise= new Promise((resolve, reject)=>{
if (true){
resolve("its resolve promise")
}else{
reject("promise is rejected")
}
})
promise.then((res)=>console.log(res)).catch((err)=>console.log(err))

Promise Chaining:- Promise chaining is if we want to handle more than one async task one by one, that time we can write Promise Chaining using then.
// returns a promise
let countValue = new Promise(function (resolve, reject) {
resolve("Promise resolved");
});
// executes when promise is resolved successfully
countValue
.then(function successValue(result) {
console.log(result);
})
.then(function successValue1() {
console.log("You can call multiple functions this way.");
});
Promise Methods:-
- Promise.all(iterable):- Waits for all promises to be resolved.
- Promise.allSettled(iterable):- Waits until all promises are resolved or rejected.
- Promise.any(iterable) :- Wait until any of the promise is fulfilled.
- Promise. race(iterable):- Wait until any of the promises are resolved or rejected.

Difference between Callback and Promise:-
What is async/await and overview of async/await :-

Ans:- Async/await are the extensions of promise.
Async:- if you use of async keyword with a function that means the function become a asynchronous function and that is always return a promise.
await:- await keyword is used inside the async function to wait for asynchronous operations. and await stop the async function until the promise returns the result.
// a promise
let promise = new Promise(function (resolve, reject) {
setTimeout(function () {
resolve('Promise resolved')}, 4000);
});
// async function
async function asyncFunc() {
// wait until the promise resolves
let result = await promise;
console.log(result);
console.log('hello');
}
// calling the async function
asyncFunc();
and in async/await we use try/catch for error handling.
// a promise
let promise = new Promise(function (resolve, reject) {
setTimeout(function () {
resolve('Promise resolved')}, 4000);
});
// async function
async function asyncFunc() {
try {
// wait until the promise resolves
let result = await promise;
console.log(result);
}
catch(error) {
console.log(error);
}
}
// calling the async function
asyncFunc(); // Promise resolved
Benefits of Using async Function:-
- The code is more readable than using a callback or a promise.
- Error handling is simpler.
- Debugging is easier.
Difference between Promise vs Async/await:-
- Promise is a Javascript object, whereas async/await is an extension of promise.
- Promise has three states- pending, fulfilled, and rejected, whereas async/await has no states, it returns the promise result.
- in Promise, we use .then and. catch for error handling, whereas in async/await we use try/catch for error handling.
- Promise chaining is difficult to understand code, whereas in async/await code is readable and easy to understand.
SetTimeout and SetInterval:-

SetTimeout:- SetTimeout is an async function that's run after the timer expires. suppose, we want to our function run after 2 seconds, that time we can use setTimeout.
ClearTimeout:- if we want to break or stop the timer at that time we can use ClearTimeout.
setTimeout(function(){
// write your code here
console.log(“I was waiting for two seconds!”);
}, 2000);
- SetInterval:- SetInterval is a timer loop, which means the function runs repeatedly until the giving time event. setInterval is continuously calling the function until clearInterval is called.
// program to display a text using setInterval method
function greet() {
console.log('Hello world');
}
setInterval(greet, 1000);
// output - Hello world
Hello world
Hello world.......



