如何在分配变量时使用async / await? [英] How can I use async/await while assigning a variable?
问题描述
我有一个变量我根据异步函数的结果设置,变量是 initialState
I have a variable I'm setting based on the result of an async function, the variable is initialState
const initialState = await getContacts()
.then((body) => {
console.log('body: ');
console.log(body);
return body;
}).catch(err => console.log(err));
我的getContacts()返回一个应该是此函数结果的promise:
My getContacts() returns a promise that should be the result of this function:
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。在我加载应用程序之前,我从数据库中获取了某种初始状态的应用程序。我应该移动这些代码并将其清理干净,但我试图快速而肮脏的测试并运行。我收到编译器错误:
I think part of my problem might be that I'm trying to call this from a plain javascript file. It is actually the index.js of my React application. I'm fetching some sort of initial state of my app from the DB before I load up the app. I should move this code and clean it up quite a bit, but I was trying to get a quick and dirty test up and running. I'm getting a compiler error:
SyntaxError:\ contact \client \ index.js:不能使用关键字'await'在异步函数之外
包含await的我的index.js是:
My index.js that contains the await is this:
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'));
推荐答案
将呼叫包裹到 getContacts ()
在异步函数中 - 您也不希望将 async / await
与 .then()混淆
,
Wrap the call to getContacts()
in an async function - you also don't want to mix up async/await
with .then()
,
(async function() {
const contacts = await getContacts();
console.log('contacts', contacts);
})();
这篇关于如何在分配变量时使用async / await?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!