-1

In my React app, i need to call 2 different functions successively for each records in my map results.

by calling the function getOrderLine() and regarding the number of records, I want to call successively the functions getItemInfo() and createOrderLine() for each records in the map results.

the expected behavior of the code below is this (we suppose we have 2 records) :

1-calling getItemInfo()
2-calling createOrderLine()
3-calling getItemInfo()
4-calling createOrderLine()

but i had this :

1-calling getItemInfo()
2-calling getItemInfo()
3-calling createOrderLine()
4-calling createOrderLine()

i tried to use async and promise but i failed to resolve the problem.

below is the code source, thank you for your help.

getOrderLine = () => {

    axios
      .post(
        this.hostname +`getPoLine.p?id=` +  this.id 
      )
      .then(response => {

        response.data.ProDataSet.tt_order_line.map( item=>{
            this.setState({
                quantity: item.quantity,
                price: item.price
            },()=>{this.getItemInfo()})
        })        
    })
  }

getItemInfo = () => {   

    /* some code */
            this.setState({

                order_code: "value 1",
                alloc_qty: 20,
            },()=>{this.createOrderLine()})
}
chonnychu
  • 1,068
  • 6
  • 10

1 Answers1

0

To run all your code in order and sequentially you need to compose the promise chain:

var getOrderLine = () => {
  axios
    .post(this.hostname + 'getPoLine.p?id=' + this.id)
    .then(response => {
      let i = 0
      next()

      function next (err) {
        if (err) {
          // an error occurred
          return
        }

        if (i >= response.data.ProDataSet.tt_order_line.length) {
          // processed all the lines
          return
        }

        const item = response.data.ProDataSet.tt_order_line[i]
        i++

        this.setState({
          quantity: item.quantity,
          price: item.price
        }, () => {
          this.getItemInfo()
            .then(() => {
              return this.createOrderLine() // assume it returns a promise
            })
            .then(next)
            .catch(next)
        })
      }
    })
}

var getItemInfo = () => {
  return new Promise(resolve => {
    this.setState({
      order_code: 'value 1',
      alloc_qty: 20
    }, resolve)
  })
}

Manuel Spigolon
  • 11,003
  • 5
  • 50
  • 73