Iterating Json object promise in javascript

Prem on 4/22/2023 8:52:48 AM

This Saturday I was practicing something I found few things challenging that way fetching data or API using JavaScript fetch promise.


It  is just a practice:

Fetch API: Get 

We will write java script function like below:

To get the data from API, we are taking dummy API from DummyJson.com you can get various API to practice.

About Fetch API

Basic syntax:

let promise = fetch(url, [options])

URL – the URL to access.

OPTIONS – optional parameters: method, headers etc.

Using fetch we can get, post, put, delete actions. but for now we are going to see the get action only.

So we are taking API URL of products: https://dummyjson.com/products

In options we are giving one header for json.

To practice this code you can paste in vs code, name the file:jspromise.js

// js promise to fetch products

async function getProduct()

{

const response = await fetch("https://dummyjson.com/products/",

{headers: { Accept: 'application/json' },});

const jsonData = await response.json();

for (const product of jsonData.products)

{

console.log("Product:"+ product.title+ " , "+"Price:"+product.price);

}

}

//calling function here

getProduct();


to run this code and see the results:

Goto terminal and navigate to js file, then write "node filenamewithextension"

> node jspromise.js



You must see the results like below screenshot.




Ref: https://javascript.info/

0 Comments on this post

Comments(0)||Login to Comments


InterServer Web Hosting and VPS
  • see more..