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

有些话、适合烂在心里 提交于 2020-05-24 07:32:48

问题


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 way to write this?

export async function getData() {
  return (dispatch) => {
    try {
      const data = await API.graphql(graphqlOperation(query))
      dispatch({ type: "DATA_AVAILABLE", data: data.data.listData.items });
    } catch(err) {
      console.log('error: ', err)
    }
  }
}

回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/56017399/how-to-fix-parsing-error-can-not-use-keyword-await-outside-an-async-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!