Promise Real Example - Fetch API + Async Await Explained
API stands for Application Programming Interface.
It is used when:
- Two applications or technologies need to share data
- It works like a bridge between them
Important Point
- When you call an API in JavaScript using
fetch() - It always returns a Promise
- You need to handle that Promise
Step-by-Step Example (Using .then())
const url = "https://dummyjson.com/products";
const apiResult = fetch(url);
console.log(apiResult);
apiResult.then((response) => {
response.json().then((result) => {
console.log(result);
});
});
Explanation:
fetch(url)→ returns a Promise- First
.then()→ gives response response.json()→ converts data (also returns a Promise)- Second
.then()→ gives final data
Short Method (Using async/await)
async function apiHandling() {
const url = "https://dummyjson.com/products";
let apiResult = await fetch(url);
apiResult = await apiResult.json();
console.log(apiResult);
}
apiHandling();
What We Learned
- API call returns a Promise
- You must handle it
.then()can be usedasync/awaitis a shorter and cleaner way