大概reportDataService.getStandardReportGridData 返回一个承诺是有原因的:它是异步的。所以很自然,在异步工作完成之前(例如,在 then 回调中),您不想清除加载标志。像这样的:
function getData() {
vm.wuDataLoading = true;
reportDataService.getStandardReportGridData(projectId, webreportIdWuSet).then(function(data3) {
vm.setRowWu01 = (formatNumber(data3.Values[0][1]));
vm.setRowWu02 = (formatNumber(data3.Values[0][2]));
})
// "finally"
.catch(e => {
// Do something about the fact the promise was rejected, but don't throw
// and don't return a rejected promise
})
.then(() => {
// Because our `catch` above converts the rejection to resolution, this gets
// called regardless of whether the original promise rejects or resolves
vm.wuDataLoading = false;
});
////some code <== This may or may not need to be in a callback above, depending on whether
// you want it to run before or after the work is complete
});
或者我需要以某种方式确保在数据完全加载之前 vm.wuDataLoading 不会更改为 false
如果其他事物也将使用相同的标志,我建议使用计数器:
function getData() {
// Increment the counter, where >0 means "loading"
++vm.wuDataLoading;
reportDataService.getStandardReportGridData(projectId, webreportIdWuSet).then(function(data3) {
vm.setRowWu01 = (formatNumber(data3.Values[0][1]));
vm.setRowWu02 = (formatNumber(data3.Values[0][2]));
})
// "finally"
.catch(e => {
// Do something about the fact the promise was rejected, but don't throw
// and don't return a rejected promise
})
.then(() => {
// Because our `catch` above converts the rejection to resolution, this gets
// called regardless of whether the original promise rejects or resolves
// Decrement the counter again
--vm.wuDataLoading;
});
////some code <== This may or may not need to be in a callback above, depending on whether
// you want it to run before or after the work is complete
});
请注意,只有在getData 中,您不打算将承诺传递给调用代码时,您才会使用上述模式。如果您这样做了(通过返回调用then 的结果),那么通过catch 这样的处理程序将拒绝转换为解决是不合适的。
在这种情况下,当 Promise 解决(无论如何)在本地函数中隔离您想要运行的任何代码,并在您的 then 处理程序和传播错误的 catch 处理程序中使用它:
function getData() {
function cleanup() {
// Decrement the counter
--vm.wuDataLoading;
}
// Increment the counter, where >0 means "loading"
++vm.wuDataLoading;
return reportDataService.getStandardReportGridData(projectId, webreportIdWuSet).then(function(data3) {
vm.setRowWu01 = (formatNumber(data3.Values[0][1]));
vm.setRowWu02 = (formatNumber(data3.Values[0][2]));
cleanup();
})
.catch(e => {
cleanup();
throw e;
});
});