[英]async await returning a Promise and not a value
在全栈应用程序上工作时,我正在调用后端,该后端从数据库检索信息并将其返回。 问题是,当我期望获得价值时,我只会得到一个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
});
}
我也找到了这个很好的答案 ,但是将其应用于我的情况仍然运气不佳。
异步函数总是返回promise; 那就是他们的工作。 存在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>
);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.