【问题标题】:How to fix Parsing error: Can not use keyword 'await' outside an async function如何修复解析错误:不能在异步函数之外使用关键字“await”
【发布时间】:2019-05-07 07:15:05
【问题描述】:

从下面的 Redux 操作代码中收到一条错误消息,指出 Parsing error: Can not use keyword 'await' outside an async function

写这个的正确方法是什么?

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

【问题讨论】:

  • return (dispatch) => { 不是async
  • return async (dispatch) => { export async function getData() 不需要异步
  • @CertainPerformance 也尝试了export const getUserJournals = () => async (dispatch) => { ... } ,但没有成功:(

标签: javascript asynchronous redux


【解决方案1】:

inner 函数需要有 async 关键字

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

【讨论】:

  • 感谢您的评论!错误消息消失了,但仍然没有从 API 获取数据...
  • 当它在我的 AWS amplify 开发环境中运行时,它实际上似乎在运行,但在我的本地运行时却无法运行。不知道为什么大声笑
  • 可能是 qraphql 查询在您的本地无法正常工作
  • 有什么想法可以在我的本地进行调试吗?
  • 这行得通!我在其他地方遇到了问题。谢谢你的回答。
【解决方案2】:

您也可以将 await 函数从 return 函数中提取出来,并将 dispatch 作为参数传递给 getData 函数。

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

那你叫它:

var dispatchFunc = function (params) {console.log(params);}
getData(dispatchFunc).then(function() {}).catch(function(err) { ... })

【讨论】:

  • 获取error: TypeError: dispatch is not a function
  • 更新了我的解释
  • 更新了我的帖子
  • 这次得到Uncaught (in promise) TypeError: dispatch is not a function
  • 但是你应该把 dispatch 作为函数传递
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-08-12
  • 1970-01-01
  • 2020-02-17
  • 2019-01-06
  • 2020-01-22
  • 1970-01-01
  • 2017-02-02
相关资源
最近更新 更多