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

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

问题描述

从下面的代码中获取一条错误消息,提示Parsing error: Can not use keyword 'await' outside an async function来执行Redux操作.

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

推荐答案

对于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天全站免登陆