TS compiler/create-react-app removes async from function

Viewed 142

I have a new react app created with create-react-app and I'm getting a compile error:

Module parse failed: Cannot use keyword 'await' outside an async function (2:562)

The problem is, the await is inside an async function as seen here:

export async function request<T>(
  path: string,
  params: RequestInit = {},
  responseHandler: (resp: Response) => Promise<ParsedResponse<T>> = getParsedResponse
): Promise<ParsedResponse<T>> {
  const resp = await fetch(path, {
    ...{
      headers: {
        Accept: "application/json"
      },
      credentials: "same-origin"
    },
    ...params
  });

  return await responseHandler(resp);
}

The output from the compiled code looks like this:

return _context.abrupt("return",function(){var resp=await fetch(path,_objectSpread({},{headers:{Accept:"application/json"},credentials:"same-origin"},{},params));return await responseHandler(resp);}());case 3:case"end":return _context.stop();}}},_callee);}));

It seems that the compiler removes the async part of the function and so we get the compiler error.

I'm not sure if there is a way around this, but other projects are using the same code and not having issues so I assume it's a configuration problem. I haven't been able to find a solution however.

Thanks for any help you can provide.

1 Answers

So, I rearranged the methods in the file and the compilation worked. I think it is related to the following babel issue:

https://github.com/babel/babel/issues/10306

I could be wrong though. In any case, it wasn't a config error or anything, just a quirk.

Related