[英]Method doesn't wait for async REST call
我在我的React应用程序中处理了很多异步调用,我希望有人澄清我遇到的一个问题。
当我尝试使用redux进行两个异步调用时遇到了这个问题。 我已经做过几次了,而且一直有效,但是这一次,异步调用被忽略了Promise
在某种程度上比我的redux动作要快。
我通过按钮调用此方法。
handle = object => { if (object) { this.edit(object); } }
然后称为编辑
edit = async object => { await this.props.createElement(object); // sets editedElement in store via REST call, then dispatches an action this.propsdoSmthElse(this.props.editedElement); // do smth with store var }
调用handle()
之后,将调用createElement()
,直到其完成,然后再调用doSmthElse()
,但是editedElement
未定义。
现在,如果我这样修改它,它就可以工作。 this.props.editedElement
不是未定义的。 因此,我只调用handle()
。 两者之间没有方法是async
。
`
handle = async object => {
if (object) {
// sets editedElement in store via REST call, then dispatches an action
await this.props.createElement(object);
// do smth with store var
this.props.doSmthElse(this.props.editedElement);
}
}
`
所有方法都在mapDispatchToProps
而this.props.editedElement
由mapStateToProps
。
const mapStateToProps = state => ({
editedElement: state.someReducer.editedElement
});
const mapDispatchToProps = dispatch => ({
createElement: object => dispatch(createElement(object)),
doSmthElse: editedElement => dispatch(doSmthElse(editedElement))
});
因此,单击按钮后立即调用这两种方法对我都有效。 如果我从另一个函数调用它们,它将以某种方式失败,并且我的存储变量未定义。 我注意到这些方法的调用顺序正确,但是第一个示例不起作用。
知道我在做什么错吗?
编辑
1)
<Button onClick={this.handle}>ClickMe</Button>
handle = object => {
if (object) {
this.edit(object);
}
}
edit = async object => {
await this.props.createElement(object);
console.log(this.props.editedElement);
this.propsdoSmthElse(this.props.editedElement);
}
`
2)
<Button onClick={this.edit}>ClickMe</Button>
edit = async object => {
await this.props.createElement(object);
console.log(this.props.editedElement);
this.propsdoSmthElse(this.props.editedElement);
}
`
console.log()
从1)打印undefined
但2)打印接收的对象。 对于这两种变体,我的减速机都能正确打印对象,并且我总是收到一个。 尝试:
edit = async object => {
await this.props.createElement(object); // sets editedElement in store via REST call, then dispatches an action
await this.propsdoSmthElse(this.props.editedElement); // do smth with store var
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.