【发布时间】:2018-04-05 09:30:34
【问题描述】:
我想从handleQuantity函数同步调用handleTotalAmount函数。请找到我的以下代码。从handleQuantity 它触发this.handleTotalAmount() 函数异步但是,我希望它被同步触发(在执行this.props.getQuantity(this.props.item.product_quantity) 之后)。但它现在按预期工作。
也添加了getQuantity Ajax API 调用。所以,从handleQauntity 函数我只想在this.props.getQuantity(this.props.item.product_quantity); 执行之后触发this.handleTotalAmount() 函数。但是,它没有发生。它以异步方式工作。
getQuantity(item)
{
ajax({
url: 'api/getQuantity',
method : 'GET',
data: {
data: JSON.stringify(item)
}
}, (data) => {
if(data.error == null )
{
//Something...
}
else {
alert(data.error);
}
});
}
handleTotalAmount()
{
this.props.totalAmountChange();
}
handleQuantity(e){
var charCode = (e.which) ? e.which : e.keyCode;
if(charCode === 13 || charCode === 9)
{
e.preventDefault();
this.props.getQuantity(this.props.item.product_quantity);
}
this.handleTotalAmount();
}
【问题讨论】:
-
我们需要查看更多您的代码。上面
handleQuantity中对this.handleTotalAmount()的调用绝对是同步的。handleQuantity似乎是一个事件处理程序,因此在调用该事件处理程序时它将是同步的,但是... -
如果 getQuantity 是一个异步函数,那么您可能会使用 async-await。比如
async handleQuantity(e){ var charCode = (e.which) ? e.which : e.keyCode; if(charCode === 13 || charCode === 9) { e.preventDefault(); await this.props.getQuantity(this.props.item.product_quantity); this.handleTotalAmount(); } }或者使用componentDidUpdate生命周期方法 -
@T.J.Crowder - 添加了
this.props.getQuantity(this.props.item.product_quantity);的Ajax api调用代码
标签: javascript reactjs