Promises:
Promises are objects in JavaScript that represent the eventual completion or failure of an asynchronous operation and its resulting value. They are used to handle asynchronous operations such as fetching data from a server, reading files, or making API calls.
Creating a Promise:
const myPromise = new Promise((resolve, reject) => { // Asynchronous operation (e.g., fetching data) setTimeout(() => { const data = 'Some data fetched from an API'; // If operation is successful, call resolve resolve(data); // If operation fails, call reject // reject(new Error('Failed to fetch data')); }, 2000); });
Consuming a Promise:
myPromise.then(data => { console.log(data); // Output: Some data fetched from an API }).catch(error => { console.error(error); });
Async/Await:
Async/Await is a syntactic sugar built on top of Promises, introduced in ES2017 (ES8). It allows writing asynchronous code that looks synchronous, making it easier to work with Promises.
Using Async/Await:
async function fetchData() { try { const data = await myPromise; console.log(data); // Output: Some data fetched from an API } catch (error) { console.error(error); } } fetchData();
Async/Await with Fetch API Example:
async function fetchUser() { try { const response = await fetch('https://jsonplaceholder.typicode.com/users/1'); if (!response.ok) { throw new Error('Failed to fetch user'); } const user = await response.json(); console.log(user); } catch (error) { console.error(error); } } fetchUser();
In the above example, fetchUser()
function fetches user data from a JSON API using fetch
API. With Async/Await, we await the response from the API, check if the response is successful, and then parse the JSON response to get the user data.
Benefits of Async/Await:
- Readable Code: Async/Await makes asynchronous code easier to read and understand, especially for developers who are more familiar with synchronous programming.
- Error Handling: Async/Await simplifies error handling by allowing the use of try/catch blocks, making it easier to handle both synchronous and asynchronous errors.
- Chaining: Async/Await allows chaining multiple asynchronous operations more easily than nested callbacks, improving code readability and maintainability.
Overall, Promises and Async/Await are powerful tools in JavaScript for handling asynchronous operations, making code more readable, maintainable, and less error-prone.
example demonstrating the use of Promises and Async/Await in JavaScript:
// Function to simulate fetching data from an API (returns a Promise) function fetchData() { return new Promise((resolve, reject) => { // Simulating an asynchronous operation (e.g., fetching data from an API) setTimeout(() => { const data = { id: 1, name: 'John Doe' }; // Simulating success resolve(data); // Simulating failure // reject(new Error('Failed to fetch data')); }, 2000); }); } // Using Promises fetchData() .then(data => { console.log('Data fetched using Promises:', data); }) .catch(error => { console.error('Error fetching data using Promises:', error); }); // Using Async/Await async function fetchAsyncData() { try { const data = await fetchData(); console.log('Data fetched using Async/Await:', data); } catch (error) { console.error('Error fetching data using Async/Await:', error); } } fetchAsyncData();
In this example:
- The
fetchData()
function returns a Promise that resolves with some data after a simulated delay. - We use Promises to handle the asynchronous operation by chaining
.then()
and.catch()
methods to handle success and failure, respectively. - We also use Async/Await to achieve the same result. The
fetchAsyncData()
function is marked asasync
, allowing us to useawait
to pause execution until the Promise returned byfetchData()
is resolved or rejected.
Both approaches achieve the same result, but Async/Await offers cleaner and more concise syntax, making the asynchronous code look synchronous and easier to understand.
0 Comments