Last active
March 1, 2024 22:14
-
-
Save g-rohit/60d2378e7132d08c5064c561ffa68014 to your computer and use it in GitHub Desktop.
Handling Promises in Javascript using Async Await, Fetch and Promise constructor.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Asynchronous function to fetch internet facts from a JSON API. | |
* @returns {Promise<void>} A Promise that resolves when the facts are fetched and logged. | |
*/ | |
async function getFacts() { | |
try { | |
// Fetch data from the internet_facts.json API | |
const API = await fetch( | |
"https://gist.githubusercontent.com/g-rohit/a4c4c49b85c71bff69738e9ad0e44da9/raw/1e74b775a2efcf1cca8b066da45aa0d28c2ac096/internet_facts.json" | |
); | |
// Extract JSON data from the API response | |
const facts = await API.json(); | |
// Log the fetched facts to the console | |
console.log("Using Async Await: ", facts); | |
} catch (error) { | |
// Handle errors by logging the error message | |
console.log(error.message); | |
} | |
} | |
// Invoke the getFacts function to fetch and log the internet facts | |
getFacts(); | |
// ===================== | |
// Writing the API response in the console using the Fetch API | |
// Fetch data from the specified URL using the Fetch API | |
fetch( | |
"https://gist.githubusercontent.com/g-rohit/a4c4c49b85c71bff69738e9ad0e44da9/raw/1e74b775a2efcf1cca8b066da45aa0d28c2ac096/internet_facts.json" | |
) | |
// Extract JSON data from the response using the json() method | |
.then((response) => { | |
// Make sure to return the promise, else the return value will be empty | |
return response.json(); | |
}) | |
// Process the JSON data received from the server | |
.then((data) => { | |
// Log the retrieved data to the console | |
console.log("Using Fetch", data); | |
}) | |
// Handle any errors that occur during the fetch operation | |
.catch((err) => { | |
// Log the error message to the console | |
console.log(err.message); | |
}); | |
// ======= | |
// Using promoises | |
new Promise((resolve, reject) => { | |
fetch( | |
"https://gist.githubusercontent.com/g-rohit/a4c4c49b85c71bff69738e9ad0e44da9/raw/1e74b775a2efcf1cca8b066da45aa0d28c2ac096/internet_facts.json" | |
) | |
.then((response) => { | |
if (!response.ok) { | |
throw new Error("Failed to fetch data!"); // this message can be shown using catch error.message | |
} | |
return response.json(); | |
}) | |
.then((data) => { | |
console.log("using promises - Facts: ", data); | |
resolve(data); | |
}).catch(error=>{ | |
reject(error) | |
}); | |
}).then(data=>{ | |
console.log('facts from chaining then to a promise: ', data); | |
}) | |
.catch((error) => { | |
console.log(error.message); // Log any errors that occurred during the fetch operation | |
}); | |
// the method using fetch and chaining .then() calls accomplishes the same task as wrapping fetch in a Promise constructor. Both approaches achieve asynchronous behavior and allow you to handle the response and potential errors. | |
// The main difference lies in the level of abstraction and flexibility that using a Promise provides: | |
// Promise Constructor: | |
// Using the Promise constructor allows you to encapsulate asynchronous operations into a reusable and composable form. This is particularly useful when you need to perform multiple asynchronous operations or when you want to abstract away the details of the asynchronous behavior. | |
// Additionally, the Promise constructor gives you explicit control over when to resolve or reject the promise based on custom logic, which can be beneficial in certain scenarios. | |
// Chaining .then(): | |
// Chaining .then() calls directly on the fetch method is a more concise and direct approach for simple asynchronous operations. It's suitable when you have a straightforward asynchronous task and you prefer a more concise syntax. | |
// However, it's worth noting that chaining .then() calls may become less readable and maintainable as the complexity of the asynchronous operations increases, especially when dealing with multiple asynchronous tasks or error handling. | |
// Both approaches are valid and have their own use cases. The choice between them depends on factors such as the complexity of the asynchronous operations, readability, and personal preference. It's important to understand both approaches and use them appropriately based on the requirements of your code. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment