【发布时间】:2016-05-25 19:16:45
【问题描述】:
在我的 React 应用程序中,我试图根据其他三个值计算一个值。我已将所有计算逻辑包含在后端,这是一个我进行异步调用的微服务。我异步尝试获取计算值的函数位于许多同步挂钩的中间。
在 UI 层,我调用了我想要返回最终结果(异步返回)的函数。被调用的函数调用另一个函数,该函数调用另一个函数,该函数返回一个新的 Promise。见以下代码:
// DateUI.js (layer 1)
selectDate(dateField, flight, idx, saved, momentTime, e) {
if (moment(momentTime).isValid()) {
if (dateField == "StartDate") {
// The initial problematic function call, need to set endDate before I continue on
let endDate = PlanLineActions.calculateFlightEndDate(periodTypeId, numberOfPeriods, momentTimeUnix);
flight.set("EndDate", endDate);
}
this.theNextSyncFunction(..., ..., ...);
}
}
// DateActions.js (layer 2)
calculateFlightEndDate(periodTypeId, numberOfPeriods, startDate) {
let plan = new Plan();
plan.getFlightEndDate(periodTypeId, numberOfPeriods, startDate).then(function(response) {
// response is JSON: {EndDate: "12/05/2016"}
response.EndDate;
}, function(error) {
log.debug("There was an error calculating the End Date.");
});
}
// DateClass.js (layer 3)
getFlightEndDate(periodTypeId, numberOfPeriods, startDate) {
let path = '/path/to/microservice';
return this.callServer(path, 'GET', {periodTypeId: periodTypeId, numberOfPeriods: numberOfPeriods, startDate: startDate});
}
// ServerLayer.js (layer 4)
callServer(path, method = "GET", query = {}, data, inject) {
return new Promise((resolve, reject) => {
super.callServer(uri.toString(),method,data,inject).then((data) => {
resolve(data);
}).catch((data) => {
if (data.status === 401) {
AppActions.doRefresh();
}
reject(data);
});
});
}
我的印象是,因为 ServerLayer.js(第 4 层)返回一个 new Promise(因此 DateClass.js(第 3 层)),所以调用 plan.getFlightEndDate(...).then(function(response) {... 在响应返回解决或拒绝之前不会完成.这目前没有发生,因为 DateUI.js(第 1 层)中的代码将继续调用 this.theNextSyncFunction,然后在大约 50 毫秒后使用正确的数据解析。
如何在继续使用 selectDate() 之前强制 DateUI.js(第 1 层)中的 PlanLineActions.calculateFlightEndDate(...) 完成响应?
【问题讨论】:
-
那些是一些疯狂的函数签名。我会考虑使用一个对象。解构对此非常有用。
-
@azium 那将是梦想。不幸的是,上面提供的代码削减了大约 75% 的当前逻辑(正如我们所说,应用程序正在重新设计),并且所有这些单独的签名(假设您正在谈论函数参数)目前都需要明确列出.如果它们包含在一个对象中,则链中的每个钩子都必须对该对象进行解构和重组,这可能会出现性能问题(但肯定会出现可读性问题)。
-
我不确定你所说的重组是什么意思。你正在做 React 所以也许你遇到过看起来像
let App = ({ someProps }) => <div>...的组件如果你有性能问题我会非常惊讶。 Ajax 调用显然是您的瓶颈。
标签: javascript asynchronous reactjs microservices