【发布时间】:2019-04-05 14:30:20
【问题描述】:
我有一个基于异步函数结果设置的变量,该变量是initialState
const initialState = await getContacts()
.then((body) => {
console.log('body: ');
console.log(body);
return body;
}).catch(err => console.log(err));
我的 getContacts() 返回一个应该是这个函数的结果的承诺:
export async function getContacts() {
let data = fetch('/api/contacts').then((data) => {
console.log(data);
return data.json();
}).catch(err => console.log(err));
return data;
}
我认为我的部分问题可能是我试图从一个普通的 javascript 文件中调用它。它实际上是我的 React 应用程序的 index.js。在加载应用程序之前,我正在从数据库中获取我的应用程序的某种初始状态。我应该移动这段代码并对其进行大量清理,但我试图让一个快速而肮脏的测试启动并运行。我收到编译器错误:
SyntaxError: \contacts\client\index.js: Can not use keyword 'await' outside an async function
包含 await 的我的 index.js 是这样的:
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import App from './components/app';
import reducers from './reducers';
import { composeWithDevTools } from 'redux-devtools-extension';
import { getContacts } from './server/api';
const initialState = await getContacts()
.then((body) => {
console.log('body: ');
console.log(body);
return body;
}).catch(err => console.log(err));
console.log('initial state: ');
console.log(initialState);
const composeEnhancers = composeWithDevTools({});
ReactDOM.render(
<Provider store={ createStore(reducers, initialState, composeEnhancers(
)) }>
<App />
</Provider>
, document.querySelector('.container'));
【问题讨论】:
-
您在设置 initialState 时使用了 await,这是错误的。正如错误所暗示的,await 只能在 async 函数中使用。检查下面@doublesharp 的答案。它的合法性。
-
@jtabuloc 是的。但之前的问题是我的后端端点不工作,我的 webpack 开发服务器有问题。
-
@VishalGulati 当我这样做时,我得到一个
Uncaught ReferenceError: regeneratorRuntime is not defined错误。我认为这是由于在 React 中使用了 async/await?至少这是我上次遇到这个问题时发现的。 -
@intA 看看这个:stackoverflow.com/a/33527883/5346095
标签: javascript reactjs express asynchronous async-await