Home > Enterprise >  Loop through array containing itemIds, fetch data from api per itemid
Loop through array containing itemIds, fetch data from api per itemid

Time:05-13

I have an array like below containing itemId's. I want to loop through the array and for every itemId fetch the corresponding data from a API and thereafter collect the results and render DOM. Can't get it working....

gtinArray = [
    "07314224054620",
    "07314225267340",
    "07313929649155",
    "07314226417799",
    "07314226224342"
]

  getItem(gtin) {
    return new Promise((resolve, reject) => {
      const URL = "http://localhost:7071/api/GetItem?Gtin="   gtin
      fetch(URL)
        .then(result => result.json())
        .then(item => {
          resolve(item)
        })
    })
  }
  

  pupulateCart() {
    let itemRequests = []

    gtinArray.forEach(gtin => {
      itemRequests.push(getItem(gtin))
    })

    Promise.all(itemRequests)
    .then(allItemData => {
      console.log("All item data")
      console.log(allItemData)
    })

  }

CodePudding user response:

const gtinArray = ["1", "2", "3", "4", "5"]

function getItem(gtin) {
  const URL = "https://jsonplaceholder.typicode.com/todos/"   gtin
  return fetch(URL).then(response => response.json());
}


async function populateCart() {
  let itemRequests = []
  itemRequests = gtinArray.map(gtin => getItem(gtin));
  return await Promise.all(itemRequests)
}

(async function () {
  const data = await populateCart();
  console.log(data);
})();

CodePudding user response:

This may be your problem, your getItem function is not in the proper format. Also any async calls need to be contained within an async function.

gtinArray = [
  "07314224054620",
  "07314225267340",
  "07313929649155",
  "07314226417799",
  "07314226224342"
]

const getItem = (gtin) => {
  return new Promise((resolve, reject) => {
    const URL = "http://localhost:7071/api/GetItem?Gtin="   gtin
    fetch(URL)
      .then(result => result.json())
      .then(item => {
        resolve(item)
      })
  })
}


async function pupulateCart() {
  let itemRequests = []

  gtinArray.forEach(gtin => {
    itemRequests.push(getItem(gtin))
  })

  Promise.all(itemRequests)
    .then(allItemData => {
      console.log("All item data")
      console.log(allItemData)
    })

}

pupulateCart();

CodePudding user response:

Solution with promises, no need for async/await (although easily convertible should you prefer that style).

const gtinArray = [
    "07314224054620",
    "07314225267340",
    "07313929649155",
    "07314226417799",
    "07314226224342"
]

function getItem(gtin) {
    const URL = "http://localhost:7071/api/GetItem?Gtin="   gtin

    // next line is to remove the external server and just give us the URL back
    // (just for the sake of StackOverflow example)
    return Promise.resolve(URL)

    // next line is what you'd actually want to make the fetch and convert json
    // return fetch(URL).then(result => result.json())
}


function populateCart() {
    // return promise, or caller can't chain 
    // (even if allItemData is processed in .then())
    return Promise.all(gtinArray.map(gtin => getItem(gtin)))
        .then(allItemData => {
            console.log("All item data")
            console.log(allItemData)
        })
}

populateCart().then(() => console.log('done'));

CodePudding user response:

To start with, huge thanks for you assistance, greatly appreciated!

I have now updated my code according to below. I still don't get it working unfortunately. When i click the button triggering the populateCart() function console.log("Running populateCart") is the only thing thats gets logged to console. I can se server side that al five requests get handled but the session never seem to close. If I kill the server I get a console error for each fetch. Please see attached screens.

enter image description here

import { LitElement, html, css} from 'lit'
import './button-done'
import './cart-item'
import { Client } from './client'
import { Queue } from './queue'

const { ipcRenderer } = window.require('electron')

export class GateApp extends LitElement {
  static get properties() {
    return {
      title: { type: String },
      customer: { type: String },
      email: { type: String },
      items: {type: Object},
      gtinArray: {type: Object},
    }
  }

  static get styles() {
    return css`
      :host {
        min-height: 100vh;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: flex-start;
        font-size: calc(10px   2vmin);
        color: #1a2b42;
        max-width: 960px;
        margin: 0 auto;
        text-align: center;
        background-color: var(--gate-app-background-color);
      }

      .frame2 {
        background-color: #CAEEC2;
      }

      #pageLayout {
        width: 100vw;
        height: 100vh;
        display: flex;
        flex-direction: column;
      }

      #frameTop {
        width: 100%;
        height: 50px;
      }

      #frameLeft {
        width: 50px;
        height: calc(100vh - 100px);
      }

      #frameRight {
        width: 50px;
        height: calc(100vh - 100px);
      }

      #frameBottom {
        width: 100%;
        height: 50px;
      }

      #centerRow {
        display: flex;
        flex-direction: row;
      }

      #content {
        width: calc(100vw - 100px);
        height: calc(100vh - 100px);
        display: flex;
        flex-direction: column;
        justify-content: center;
      }

      #cartItemContainer {
        width: calc(100vw - 100px);
        display: flex;
        flex-wrap: wrap;
        flex-direction: row;
        justify-content: center;
        align-content: flex-start;
      }

      .cart-item {
        margin: 15px;
        box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.2), 0 4px 20px 0 rgba(0, 0, 0, 0.19);
        border-radius: 5px;
      }
    `
  }

  constructor() {
    super()
    this.title = 'Shoppingbag'
    this.customer = ''
    this.email = ''
    
    this.items = []
    //this.gtinArray = []
    this.gtinArray = ['07314224178272', '07314227150152', '07314227475811', '07314228873272', '07314227368533']

    this.client = new Client()
    this.gtinQueue = new Queue()
    this.timer
  }

  firstUpdated() {
    ipcRenderer.on("new-scan", (_, tag) => {
      //console.log("Received message from Electron: ", tag)
      
      if (this.isBag(tag)) {
      
      } else {
        this.handleScan(tag)
      }

    })

  }

  render() {
    return html`
      <div id="pageLayout">
        <div id="frameTop" ></div>
        <div id="centerRow">
          <div id="frameLeft" ></div>
          <div id="content">

            <h1>${this.title}</h1>
            <div id="cartItemContainer">
              
              ${this.items.map(item => html`
              
              <cart-item
                
                imageUrl="${item.assetUrl}"
                itemName="${item.productName}"
                itemPrice="${item.whitePrice}"
                artNr="${item.articleId}"
                size="Medium"
              ></cart-item>
              
              `)}

            </div>
            <br>
            <button-done @click="${this.populateCart}"></button-done>

          </div>
          <div id="frameRight" ></div>
        </div>
        <div id="frameBottom" ></div>
        </div>
    `
  }

  itemInCart(gtin) {
    let itemInCart = false
    this.items.forEach(item => {
      if (item.gtin === gtin) {
        itemInCart = true
      }
    })
    return itemInCart
  }

  isBag(tag) {
    if (tag.substring(0, 2) === '00')
      return true
    else
      return false
  }

  handleScan(tag) {
    var found = false
    this.gtinArray.forEach(gtin => {
      if (gtin == tag) {
        found = true
      }
    })

    if(!found) {
      this.gtinArray.push(tag)
      this.gtinQueue.enqueue(tag)
        clearTimeout(this.timer)
        this.runTimer()
      console.log(this.gtinArray)
    }
  }

  getItem = (gtin) => {
    return new Promise((resolve, reject) => {
      const URL = "http://localhost:7071/api/GetItem?Gtin="   gtin
      fetch(URL)
        .then(result => result.json())
        .then(item => {
          resolve(item)
        })
        
    })
  }
  
  async populateCart() {
    console.log("Running populateCart")
    let itemRequests = []
  
    this.gtinArray.forEach(gtin => {
      itemRequests.push(this.getItem(gtin))
    })
  
    Promise.all(itemRequests)
      .then(allItemData => {
        console.log("All item data")
        console.log(allItemData)
      })
  
  }

}

customElements.define('gate-app', GateApp)
  • Related