正在使用全栈应用程序,我正在调用后端,该后端从数据库检索信息并将其返回。问题是,当我期望获得价值时,我只会得到Promise {<pending>}
。我已经在后端代码上验证了我实际上从数据库获得了响应并将其发送回前端,因此我不确定为什么诺言没有得到解决。有任何想法/建议吗?
这是我要调用后端并显示信息的组件。 console.log
显示Promise {<pending>}
getTheAsset = async id => {
try {
const response = await this.props.getAsset(id)
.then(result => {
console.log("[DisplayAsset] Promise result: ", result);
});
} catch(error) {
console.log("[DisplayAsset] error: ", error);
}
}
render() {
const asset = this.getTheAsset(this.props.match.params.id);
console.log("[DisplayAsset] asset - ", asset);
return (
<div className="container">
</div>
);
}
以下是进行API调用的redux操作。
export const getAsset = (id) => async dispatch => {
const response = await axios.get(`http://localhost:8181/api/asset/${id}`);
dispatch({
type: GET_ASSET,
payload: response.data
});
}
我也发现answer非常好,但运气还不足以解决我的情况。
答案 0 :(得分:5)
异步函数总是返回承诺;那就是他们的工作。存在Async / await来简化与承诺有关的语法,但它不会改变涉及承诺的事实。
对于react组件,您需要有一个状态值,该状态值开始时指示尚未加载,然后启动异步工作,并在完成后更新状态。如有必要,可以在加载时渲染占位符。
state = {
asset: null,
}
componentDidMount() {
this.getTheAsset(this.props.match.params.id)
.then(result => this.setState({ asset: result });
}
render() {
if (this.state.asset === null) {
return null; // or some other placeholder.
} else {
return (
<div className="container">
</div>
);
}
}