Do you think IIT Guwahati certified course can help you in your career?
No
Introduction
In JavaScript, a promise represents the eventual completion or failure of an asynchronous operation. Async/await simplifies writing asynchronous code, offering a more readable and concise syntax.
To improve the user experience and fast rendering, we use asynchronous functions.
Promise Functions
Promise handles asynchronous operations that still need to be completed, and their results may be available after a period of time. It is essential for handling AJAX requests, timeouts, and other asynchronous operations.
Promises have three states: pending, fulfilled, and rejected. It always starts in the pending state when it is created. When the asynchronous operation completes successfully, the Promise transitions to the fulfilled state and passes the resulting value to the success callback function. If the process fails, the Promise transitions to the rejected state and passes an error object to the error callback function.
A Promise can only change from the pending state to either the fulfilled or rejected state. Once it has transitioned to either of these states, it cannot change to any other state. For a detailed explanation of Promises, visit this blog.
Example Code
const ninjaPromise = new Promise((resolve, reject) => {
// Do some asynchronous operation
if (/* operation is successful */) {
resolve('Here comes the success!');
}
else {
reject('Oops we have an Error!');
}
});
ninjaPromise.then(result => {
console.log(result); // Output: Here comes the success!
}).catch(error => {
console.error(error); // Output: Oops we have an Error!
});
You can also try this code with Online Javascript Compiler
In the above code, ninjaPromise( ) is a promise object created using the Promise constructor. It takes two parameters reject and resolve. Inside the function, an asynchronous operation is performed. If the operation is successful resolve is called with the success message else reject is called with an error message. The then method is called to attach the callback function if the promise is resolved else catch method is called to attach the callback function if the promise is rejected.
When executing multiple promises one after the other, we use a Promise chain, where we have to use multiple .then( ) statements. Sometimes, a Promise chain can become lengthy and complicated, making it harder to read and debug. This is where async await comes in.
Async/Await Functions
You must have heard that “Async Await is a syntactic sugar on top of Promises”. It makes the asynchronous code easier to read, write, and maintain asynchronous code. Instead of chaining Promises together, Async Await allows developers to write code that looks like synchronous code.
Async Await uses only two keywords: async and await. The async keyword is used to declare that a particular function is asynchronous. The await keyword waits for the execution of the async function’s code block until a promise is fulfilled or rejected.
Example Code
const fetchData = async () => {
try {
const response = await fetch('https://api.ninjaimages.com/data');
const data = await response.json();
return data; // Output: returns the fetched data
}
catch (error) {
console.log(error); // Output: returns the error message
}
}
You can also try this code with Online Javascript Compiler
In the above code, fetchData( ) is an asynchronous function. It will return a promise using the try-catch block. Inside the function, a try block is used to attempt to fetch data from an API endpoint using the fetch function. The URL for the endpoint is “https://api.ninjaimages.com/data”. The await keyword is used to wait for the fetch to complete and for the response to be returned. The response object is stored in the response variable and returned. If any error occurs in the try block, then catch block will be executed and the error will be returned.
Difference Between Promise and Async/Await
Here are some notable differences between Promise vs Async Await:
Parameter
Promise
Async Await
Syntax
The promise involves chaining .then and .catch methods, which can make the code look complicated and hard to read.
Async Await uses a simpler syntax that looks more like synchronous code.
Error Handling
Error handling is done using the .catch method, which can make the code look cluttered.
Error handling is done using a try-catch block, which makes the code cleaner and easier to read.
Control flow
Promises use a chain of .then methods to control the flow of execution. This can make it difficult to follow the order of operations.
With async/await, the code looks more like synchronous code. In try-catch, all await functions are kept inside. There is no need for chained try blocks.
Error Propagation
Errors propagate down the chain of .then methods until they are caught by a .catch method. This can make it challenging to find the source of the error.
Errors are propagated up the call stack, making it easier to find the source of the error.
Sync and Async Functions
In advanced programming languages, there are two kinds of function behaviour, synchronous and asynchronous. In javascript context, when a synchronous function is called, the code execution is paused until the function returns. It means that the main thread is blocked, and other functions cannot be executed until the current operation has been completed.
On the other hand, asynchronous functions are non-blocking. When an asynchronous function is called, the function returns immediately without blocking the main thread. The function may take some time to complete, like fetching an image from the server, and the code execution continues in the meantime. When the function completes, it triggers a callback function or a promise, which allows the calling code to continue with the result. For further information, visit this blog.
Frequently Asked Questions
What is a Promise in JavaScript?
A Promise represents the completion or failure of an asynchronous operation. It will be in one of three states: pending, resolved, or rejected.
What is Async Await in JavaScript?
Async Await is a newer feature introduced in ECMAScript 2017 (ES8) that simplifies the use of Promises in JavaScript. It makes the asynchronous code easier to read, write, and maintain.
What is the syntax difference between Promise and Async Await?
The promise involves chaining .then and .catch methods, whereas Async Await uses a try-catch block that looks more like synchronous code.
Which one should I use, Promise or Async Await?
It is a personal preference. Sometimes, Promises may be more suitable for simpler asynchronous operations, whereas Async Await can be more suitable for complex asynchronous operations.
How is error handling different between Promise and Async Await?
With Promises, error handling is done using the .catch method, whereas with Async Await, error handling is done using a try-catch block.
Conclusion
In this article, we briefly discussed asynchronous functions and how they led to the development of Promises and Async Await. We also discussed the difference between Promises and Async Await. For a better understanding, you should code it yourself.