Last active
August 10, 2023 03:38
-
-
Save sakshstore/303811e9c4f56eac66a440923aeed77c to your computer and use it in GitHub Desktop.
async/await is a modern approach to handle asynchronous code, making it look more synchronous and easier to read.
This file contains hidden or 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
// Longhand | |
function fetchData() { | |
return fetch('https://api.example.com/data') | |
.then((response) => response.json()) | |
.then((data) => { | |
console.log(data); | |
}) | |
.catch((error) => { | |
console.error(error); | |
}); | |
} | |
// Shorthand | |
async function fetchData() { | |
try { | |
const response = await fetch('https://api.example.com/data'); | |
const data = await response.json(); | |
console.log(data); | |
} catch (error) { | |
console.error(error); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment