fueanta

JavaScript IIFE and Async-await Demo

Apr 8th, 2020
195
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // IIFE and Async-await demonstration
  2. (async (url) => {
  3.     const headers = new Headers()
  4.     headers.append('Content-Type', 'application/json')
  5.     headers.append('Accept', 'application/json')
  6.  
  7.     try {
  8.         const response = await fetch(url, {
  9.             mode: 'cors',
  10.             method: 'GET',
  11.             headers: headers
  12.         })
  13.  
  14.         const data = await response.json()
  15.         const productList = document.querySelector("#product-list")
  16.  
  17.         data.forEach((product) => {
  18.             productList.innerHTML += `<h3>Product No: ${product.id}</h3>`
  19.             productList.innerHTML += "<ul>"
  20.             productList.innerHTML += `<li>Product Name: ${product.name}</li>`
  21.             productList.innerHTML += `<li>Status: <label style="color: ${product.isSold ? "red" : "green"}; font-weight: bold;">${product.isSold ? "Out of stock" : "Available"}</label></li>`
  22.             productList.innerHTML += "</ul>"
  23.         })
  24.     } catch (error) {
  25.         console.log(error)
  26.     }
  27. })("http://127.0.0.1:3000")
RAW Paste Data