Home Courses Promise Real Example - Fetch API + Async Await Explained

Promise Real Example - Fetch API + Async Await Explained

API stands for Application Programming Interface.

It is used when:

  1. Two applications or technologies need to share data
  2. It works like a bridge between them


Important Point

  1. When you call an API in JavaScript using fetch()
  2. It always returns a Promise
  3. 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:

  1. fetch(url) → returns a Promise
  2. First .then() → gives response
  3. response.json() → converts data (also returns a Promise)
  4. 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

  1. API call returns a Promise
  2. You must handle it
  3. .then() can be used
  4. async/await is a shorter and cleaner way


Share this lesson: