As we know that the JavaScript is single-threaded and can only handle one operation at a time. As there is a single execution thread for our program to run, a question arises that how to execute a long-running operation without blocking the thread of execution?
synchronous and asynchronous programming?
In synchronous programming, one thing happens at a time.
When we call a function that performs a long-running action, it returns a result when the action has finished. This stops the program for the time the action takes. In contrast, asynchronous programming allows multiple things to happen at the same time. When we start an action, the program continues to run. When the action finishes, the program is informed and gets the result.
In synchronous programming, where the request function returns only after it has done its work. To perform this task, we make the requests one after the other. Here the drawback is that the second request will be started only when the first has finished. Suppose the time taken by the first request is 12 seconds, and the time taken by the second request is 13 seconds, so the total time taken will be the sum of the two response times.
In asynchronous programming, the functions that perform a slow action takes an extra argument, a callback function. The action is started, and when it finishes, the callback function is called with the result.
setTimeout(() => console.log("Testing"), 500);
3 type Asynchronous Programming
- Asynch/await
- Callbacks
- promise
Asynch/await
Async/await functions, which is a new addition with ES2017. that help us even more in allowing us to write completely synchronous-looking code while performing asynchronous tasks behind the scenes. The async function always returns a promise.
async function name(param1, param2, ...paramN) {
// statements
}
- name - This is the name of the function
- param – This is the parameters that are passed to the function
async function func() { console.log('Async/Await tutorial.'); return Promise.resolve(1); } func();
The await keyword: The await keyword is used to wait for the asynchronous operation. This keyword is used inside the async function. Here is the syntax to use await is:
The await pauses the async function until the promise returns a result value. When we want to call this function, we prepend await, and the calling code will stop until the promise is resolved or rejected.
async function pradeep(){
console.log('Inside the pradeep Function');
const response = await fetch('https://jsonplaceholder.typicode.com/users');
console.log('before the response');
const users = await response.json();
console.log('user resolved');
return users;
}
console.log('Before calling pradeep function');
let test = pradeep();
console.log('After calling pradeep function');
console.log(test);
test.then(data=>{
console.log(data);
});
console.log('Last line of this code');
/* outputs: Before calling pradeep function
Inside the pradeep Function
After calling pradeep function
return users;
Last line of this code
before the response
user resolved
console.log(data);
*/
What is a Callback?
A callback is a function that is executed after another function has finished executing. As we have studied earlier that functions are objects. Functions can take functions as arguments and can be returned by other functions. Functions that take another function as an argument are called higher-order functions. So, the callback function can also be defined as any function that is passed as an argument is called a callback function.
const students = [
{name: 'pradeep', subject:'JavaScript'},
{name:'Neha', subject:'Account'},
{name:'Kaivallya', subject:'Poem jr kg'},
{name:'Ashwat', subject:'Playing football'}
];
console.log('===== for each function also callback function====');
students.forEach((element) => {
console.log(element);
})
console.log('==== finish for each function====');
function enrollstudents(student){
setTimeout(() => {
students.push(student);
},2000);
}
function getFunction(){
setTimeout(() => {
let str = '';
students.forEach((student) => {
str += ` <li>${student.subject} and Subject is ${student.subject} </li> `;
document.getElementById('students').innerHTML = str;
})
},1000);
}
let newStudent = {name:'Rohit', subject:'Angular'};
enrollstudents(newStudent);
getFunction();
/*-- Note: all print like pradeep and Subject is JavaScript but new student not show
becouse of settime out enrollstudents 2000ms and getFunction 1000ms first show than enrollstudents than show */
OutPut:
- pradeep and Subject is JavaScript
- Neha and Subject is Account
- Kaivallya and Subject is Poem jr kg
- Ashwat and Subject is Playing football
- Rohit and Subject is Angular
Promise
Promises is a way through which we can deal with asynchronous operations in JavaScript. When we make a promise, it is a guarantee that in future, we are going to do something. A promise has two possible outcomes: it will be kept when the time comes, or it will not. Similarly, in JavaScript, when we define a promise, either it will be resolved when the time comes, or it will get rejected. “the Promise object represents the eventual completion (or failure) of an asynchronous operation and its resulting value.”
let myPromise = new Promise(function(resolve, reject) {
// code here
});
A promise has three states:
- pending: It is the initial state.
- Fulfilled: It indicates that the promised operation was successful.
- Rejected: It indicates that the promised operation was unsuccessful.
const students = [
{ name: "Pradeep", subject: "JavaScript" },
{ name: "Ashwat", subject: "Machine Learning" }
]
function enrollStudent(student) {
return new Promise(function (resolve, reject) {
setTimeout(function () {
students.push(student);
console.log("Student has been enrolled");
const error = false;
if (!error) {
resolve();
}
else {
reject();
}
}, 1000);
})
}
function getStudents() {
setTimeout(function () {
let str = "";
students.forEach(function (student) {
str += `<li> ${student.name}</li>`
});
document.getElementById('students').innerHTML = str;
console.log("Students have been fetched");
}, 5000);
}
let newStudent = { name: "Kevu", subject: "Python" }
enrollStudent(newStudent).then(getStudents).catch(function () {
console.log("Some error occured");
});
Comments
Post a Comment