node.js - 试图检索异步/等待的结果
问题描述
我正在尝试使用 async / await 从 Promise 中检索结果,但收到以下错误:
544:1 未捕获的错误:模块构建失败:语法错误:等待是保留字 (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>
);
}
}
我可以运行上述内容,但前提是我返回结果并在实际异步函数中设置状态。如何在该函数之外返回承诺的结果?
谢谢!
解决方案
await
只能在用 . 声明的函数内部使用async
。所以你应该在这个函数中使用 await 来获取你的数据并设置状态。此外,您的代码也不是最优的,因为它会尝试在每次重新渲染组件时接收数据。更好地构建您的类并使用生命周期方法,例如componentDidMount
获取数据并将其存储到状态。然后在渲染中只使用状态来显示它
export default class WhereSheGoes extends React.Component {
constructor (props) {
super(props);
this.state = {
destinations: '',
posts: '',
globals: '',
}
}
componentDidMount() {
retrieveBucket();
}
retrieveBucket = async () => {
const bucket = Cosmic.bucket({
slug: 'where-she-goes',
read_key: '',
write_key: ''
});
try {
let result = await bucket.getBucket()
console.log(result)
this.setState ({
destinations: _.filter(result.bucket.objects, {type_slug: 'destinations'}),
posts: _.filter(result.bucket.objects, {type_slug: 'posts'}),
globals: _.filter(result.bucket.objects, {type_slug: 'globals'})
});
} catch (err) {
console.log(err)
}
}
render() {
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>
);
}
}```
推荐阅读
- python - 如何检查 RGB 颜色列表中的所有项目是否在没有循环的图像中?
- verilog - 划分一个verilog genvar
- sql - postgreSQL 反转 REGEXP_SPLIT 到表
- python - 比较来自两个数据集的两组属性并使用匹配更新第三个数据集
- rust - 如何消除泛型特征方法调用的歧义?
- c++ - 在构造函数c ++中初始化属性时出现问题
- c# - 在 transform.position 更改后,Unity 播放器/精灵变得不可见。如何防止玩家消失?
- python - 将临时文件永久保存,以便应用程序以后可以获取它
- sql - SQL如何在一个查询中从列表中执行多个查找
- scala - 使用 when 子句有什么问题