如何修复解析错误:不能在异步函数外使用关键字“await" [英] How to fix Parsing error: Can not use keyword 'await' outside an async function

查看:46
本文介绍了如何修复解析错误:不能在异步函数外使用关键字“await"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从下面的 Redux 操作代码中收到一条错误消息,指出 解析错误:不能在异步函数外使用关键字await".

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

正确的写法是什么?

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

推荐答案

inner 函数需要有 async 关键字

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

这篇关于如何修复解析错误:不能在异步函数外使用关键字“await"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆