[英]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.