我正在尝试使用异步/等待和我的代码工作,我只是需要一些建议,这是使用异步/等待的正确方式,还是我这里需要.then。我有一个函数loadDataForExport -它返回promise和生成的数据。此外,我还有带有异步事件函数的等待,其中我使用了asyn/ actionButtons,因为在其他情况下是let data = loadDataForExport() - return promise。
loadDataForExport = async () => {
const {sort, search} = this.state
let dataForExport = await this.props.load({pageSize: this.props.totalCount, skip: 0, sort, search}).then(({entities: {devices, rooms}}) => Object.values(devices).map(({deviceType, deviceId, name, version, location, lastAliveMessage, deviceStatus}) => ({
deviceType,
deviceId,
name,
currentVersion: version,
location: location && rooms[location] ? rooms[location].name : '',
lastAliveMessage,
deviceStatus,
})))
return dataForExport
}
const actionButtons = loadDataForExport => [
{
event: async () => {
let data = await loadDataForExport()
exportToExcel(data)
},
name: 'exportToExcel',,
},
]发布于 2018-02-06 19:12:23
从我对async/await如何工作的理解(太少)来看,你做得很对。我相信以下是正确的,如果我错了,请随时纠正我(我已经准备好支付一些减价,以更好地了解它是如何工作的):
Await将等待(通过生成器的方式)在执行异步函数的下一条语句之前解析给定的promise。
因此,let dataForExport = await this.props.load(...)会将this.props.load(...)的解析值赋给dataForExport。
异步函数loadDataForExport将返回一个promise,该promise将使用dataForExport的值进行解析,或者使用rejected this.props.load()的值进行拒绝,您可以像在loadDataForExport.event()中一样将其与await一起使用
https://stackoverflow.com/questions/48641328
复制相似问题