How to fix Parsing error: Can not use keyword 'await' outside an async function

后端 未结 2 1324
栀梦
栀梦 2021-01-29 09:41

Getting a error message saying Parsing error: Can not use keyword \'await\' outside an async function from below code for Redux action.

What is the proper w

相关标签:
2条回答
  • 2021-01-29 09:53

    You need to have async keyword for the inner function

    export function getData() {
      return async (dispatch) => {
        try {
          const data = await API.graphql(graphqlOperation(query))
          dispatch({ type: "DATA_AVAILABLE", data: data.data.listData.items });
        } catch(err) {
          console.log('error: ', err)
        }
      }
    }
    
    0 讨论(0)
  • 2021-01-29 10:03

    You can pull your await function out of your return function as well and pass dispatch as a param to getData function.

    export async function getData(dispatch) {
      const data = await API.graphql(graphqlOperation(query))
      dispatch({ type: "DATA_AVAILABLE", data: data.data.listData.items });
    }
    

    then you call it:

    var dispatchFunc = function (params) {console.log(params);}
    getData(dispatchFunc).then(function() {}).catch(function(err) { ... })
    
    0 讨论(0)
提交回复
热议问题