JavaScript is mainly single threaded that means only one line of code can be run in a given time. Which kind of spoils the user experience as the process becomes slow. For example: when we call function in sequence i.e., in a synchronous manner in that case until the previous function gets executed or returns something the next function wont get executed.
But with the help of Promises and Async/Await JavaScript can perform long sequenced requests without any hurdles or waiting for any function in the sequence. which makes he process way more fast.
Promises in JavaScript
"I promise a result !" is what it basically means, Promise is an asynchronous action of ES6 that may complete at some point in future and produce a value when its completed. Promise object returns a function which takes two parameters one for resolve and other for reject. When executing code obtains a result any one of this callback gets called. if it obtains result then the result is contained by resolve callback whereas for reject it will be error object. Now, when the promise is resolved then the ".then" method is called which runs a result (a callback function for success). When the promise gets rejected then the .catch method is called which will run a callback function for error handling.
NOTE: The .then method can also callback both the function without using catch one with parameter value and other one with error.
Here is an example to explain it all.
let code = new Promise(function(resolve, reject){
let compile=true;
if(compile)
resolve()
else
reject()
});
code.then(function(){
document.write("compilation Successful !")
}).catch(function(){
document.write("compilation Error !")
})
Async/Await in JavaScript
Async/Await is a new way of writing asynchronous code introduced with ES7. It works just like promises but the syntax has been polished on top of promises to make it easier to implement nested Promises or many async Promises. It helps developers to write a cleaner , more readable code and easier to handle than promises
According to MDN..
An async function can contain an await expression that pauses the execution of the async function and waits for the passed Promise's resolution, and then resumes the async function's execution and evaluates as the resolved value.
A function that returns a promise can be written as async function function_name(){
await some_promise()
}
You don't need to provide any callbacks or .then methods to run code after asynchronous operation is done, when we put async
keyword before a function declaration, it will return a promise and we use the await
keyword inside it which blocks the code until the promise inside which await
is declared gets resolved or rejected.
The await keyword is only valid inside async functions. If you use it outside of an async function's body, you will get a SyntaxError.
Here is a example to explain how it works!
let result = function(score){
return new Promise(function(resolve,reject){
console.log("calculating results...")
if(score>40)
resolve("You have Passed !")
else
reject("You have Failed !")
});
}
async function calculateResults(){
try{
const response = await result(60)
console.log("Results Recieved ! "+ response)
}
catch(err){
console.log(err)
}
}
calculateResults()
In this above code try and catch is used for error handling try
runs the code inside it no matter what and catch
catches the error which is recieved when promise gets rejected
Conclusion
Async/Await is one of the most revolutionary thing that has been added to JavaScript to provide replacement for Promises.
Why ???
- It makes us realize how mess nested promise can be syntactically.
- Error handling can be done both in synchronous and asynchronous way.
- Conditionals (code which fetches some data and based on that decides whether to return that data or fetch some more value in the data) becomes much more readable in contrast to promises.
- Error stacks in promise is difficult to track exactly in which promise function the error occured whereas using async/await it points out to the function which contains the error.
- Last but not the least Its much easier to debug when using async/await that makes it stand out from promises.