简体   繁体   中英

React component async await in other funtion

Quick question about async await, there are a lot of examples to use async await with React, but I have trouble to get it working.

componentDidMount = () => {

    const cards = mockCards;

    this.setState(
        {
            loading: false,
            cointrackerCards: [
                ...cards.map(
                    card => {
                        const price = await this.getCurrentSellPrice(card.coin, card.valuta, card.amount[card.coin])
                        return {
                            ...card, 
                            currentSellPrice: price
                        }
                    }
                )
            ]
        }
    )

}

getCurrentSellPrice = async (coinType, valuta, amount) => {
    //console.log(coinType, valuta, amount)
    try {
        const result = await coinbaseAPI.get('/prices/BCH-EUR/sell')
        //console.log(result.data.data)
        return result.data.data.amount
    }
    catch (err) {
        console.log('[ERRORHANDLER]', err)
    }
}

The above code throws a error: Syntax error: await is a reserved word (71:42) Directly calling the function in the currentSellPrice key, does not work either, as it returns a Promise. What am I doing wrong?

Your problem: you can't await ing something without async scope, this is what you do in/with componentDidMount . If you would like to use await inside componentDidMount mark it as async . Here is a working example of how it works:

class AsyncState extends React.Component {
  state = {
    flag: false
  }

  async componentDidMount(){
    const flag = await this.changeFlagAsync();
    this.setState({flag})
  }

  async changeFlagAsync(){
    return new Promise((resolve, reject) => { // simulate async
      setTimeout(() => resolve(true), 2000)
    })
  }

  render() {
    return <div>
      {this.state.flag && <div>Done after 2 sec</div> || <div>Waiting for promise</div>}
    </div>;
  }
}

Also working fiddle

You are making two mistakes first is you didn't assign async keyword to the function. at cards.map.

anyways I guess it won't work even if you write it there because async await won't work in map use for in, for of or traditional for loop for doing this.

refer to this answer Using async/await with a forEach loop

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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