【发布时间】:2019-10-11 20:40:51
【问题描述】:
我正在尝试使用 async / await 从 Promise 中检索结果,但收到以下错误:
544:1 未捕获的错误:模块构建失败:SyntaxError: await 是保留字 (30:23)
这是我的代码:
import React from 'react';
import Header from './Header';
import Feed from './Feed';
import _ from 'lodash';
const Cosmic = require('cosmicjs')();
export default class WhereSheGoes extends React.Component {
constructor (props) {
super(props);
this.state = {
destinations: '',
posts: '',
globals: '',
}
}
render() {
const bucket = Cosmic.bucket({
slug: 'where-she-goes',
read_key: '',
write_key: ''
});
const retrieveBucket = async () => {
try {
let result = bucket.getBucket()
return result
} catch (err) {
console.log(err)
}
}
const result = await retrieveBucket()
console.log(result)
this.setState (() => {
return {
destinations: _.filter(result.bucket.objects, {type_slug: 'destinations'}),
posts: _.filter(result.bucket.objects, {type_slug: 'posts'}),
globals: _.filter(result.bucket.objects, {type_slug: 'globals'})
}
});
return (
<div>
<Header
destinations={this.state.destinations}
posts={this.state.posts}
globals={this.state.globals}
/>
<Feed
posts={this.state.posts}
destinations={this.state.destinations}
/>
</div>
);
}
}
我可以让上面的代码运行,但前提是我返回结果并在实际的异步函数中设置状态。如何在该函数之外返回 promise 的结果?
谢谢!
【问题讨论】:
-
嗯,我相信你只能在
async函数中使用await...
标签: node.js reactjs async-await