Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
595 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...