反应组件异步等待其他功能



关于异步等待的快速问题,有很多示例可以在 React 中使用异步 await,但我很难让它工作。

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

上面的代码抛出了一个错误:Syntax error: await is a reserved word (71:42)直接调用currentSellPrice键中的函数也不起作用,因为它返回一个 Promise。我做错了什么?

你的问题:你不能在没有async范围的情况下await某事,这就是你在componentDidMount中/与一起做的事情。如果要在内部使用awaitcomponentDidMount请将其标记为async。以下是其工作原理的工作示例:

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

working fiddle

你犯了两个错误,首先是你没有为函数分配async关键字。

无论如何,我想即使您在那里编写它,它也不起作用,因为异步 await 在地图中使用 in、for 或传统的 for 循环中不起作用。

参考此答案 将 async/await 与 forEach 循环结合使用

最新更新