2

I am trying to use async/await and my code works, I just need advice about is it the right way to use async/await, or do I need .then here. I have a function loadDataForExport - that return promise with generate data. Also, I have actionButtons with async event function, where I use asyn/await because in other case 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',,
    },
]
str
  • 42,689
  • 17
  • 109
  • 127
Palaniichuk Dmytro
  • 2,943
  • 12
  • 36
  • 66

1 Answers1

3

From my (too little) understanding of how async/await works, you are doing it the right way. I believe the following is true, feel free to correct me if i'm wrong (I'm ready to pay a few downvotes to get a better understanding of how it works) :

Await will wait (by the means of generators) for the given promise to be resolved before executing the next statement of the async function.

Thus, let dataForExport = await this.props.load(...) will assign the resolved value of this.props.load(...) to dataForExport.

Async function loadDataForExport will return a promise that will either resolve with the value of dataForExport or reject with the value of the rejected this.props.load(), which you can use with await just like you do in loadDataForExport.event()

Logar
  • 1,248
  • 9
  • 17
  • 2
    Assign the resolved value of load is correct but the loadDataForExport function will immediately return a promise. If load causes an error or returns a rejected promise than the promise returned by getProresultByseriesFamily will reject as well. – HMR Feb 06 '18 at 11:24
  • @HMR right, thanks. Tried to edit my answer according to your comment – Logar Feb 06 '18 at 11:32