Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
592 views
in Technique[技术] by (71.8m points)

node.js - Foreach Loop not working correct in Javascript with axios request

I'm trying to execute a functionality to make a sale in my app but in this sale a want make a count based in the price in the products that I have before the sale. But the only problem is that the value of the sale are not coming before the createSale execution and when I try to send the json updated not working

here is my code:

  async function calculatePrice(sale) {
    
      axios({
          method: 'post',
          url: 'http://localhost:3000/dev/calculate',
          data: sale,
        })
          .then(response => {
            console.log(response.data)

            return response.data
              
            })
            .catch(error => {
              console.log(error)

              return error
            })

        
  }

async function createSale() {
    
    let json = {
      guest_name: document.getElementById('guest_name').value,
      room_number: document.getElementById('room_number').value,
      products: [{
        id: document.getElementById('sale_products').value,
        quantity: document.getElementById('quantity').value,
      }
      ],
      status: true
    }

    let products = json.products;
    let total_sale = 0
    await products.forEach((sale) => {
      total_sale = total_sale + calculatePrice(sale)
    })
  
    console.log('sale: ', total_sale)
        //this execution should be after the foreach
    axios({
      method: 'post',
      url: 'http://localhost:3000/dev/sale',
      data: json,
    })
      .then(response => {
          console.log(response)
          $(".products").html("");
          getProducts()
          alert('success sale!')
        })
        .catch(error => {
          alert('failure sale!')
          console.log(error)
        })
    event.preventDefault()
  }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...