简体   繁体   English

React.js,如何使用 map 和带有 setState 回调的异步函数?

[英]React.js, how to use map and async functions with setState callback?

In my React app, i need to call 2 different functions successively for each records in my map results.在我的 React 应用程序中,我需要为 map 结果中的每条记录连续调用 2 个不同的函数。

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.通过调用 function getOrderLine() 和关于记录数,我想为 map 结果中的每条记录依次调用函数 getItemInfo() 和 createOrderLine()。

the expected behavior of the code below is this (we suppose we have 2 records):下面代码的预期行为是这样的(我们假设我们有 2 条记录):

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

but i had this:但我有这个:

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

i tried to use async and promise but i failed to resolve the problem.我尝试使用 async 和 promise 但我未能解决问题。

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()})
}

To run all your code in order and sequentially you need to compose the promise chain:要按顺序运行所有代码,您需要编写 promise 链:

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)
  })
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM