提问人:Phú Huỳnh Gia 提问时间:10/26/2023 更新时间:10/26/2023 访问量:34
Javascript 异步提交函数在 forEach 循环中无法等待完成 (Vue)
Javascript async submit function cannot wait for finishing in forEach loop (Vue)
问:
在我的 Vue 项目中,我有一个日期字符串数组和一个异步函数this.dateList
importLaborDtl(dsLaborHed, dsLaborDtl) {
let that = this;
setTimeout(() => {
global.loaderMsg(global.L('submitting'));
}, 100);
that.busy = true;
that.$forceUpdate();
// console.trace(dsLaborHed, dsLaborDtl);
imp
.importTime(dsLaborHed, dsLaborDtl)
.then((res) => {
global.loaderHide();
if (global.showErr(res)) {
console.trace(res);
that.busy = false;
that.$forceUpdate();
return;
}
global.toast(global.L('sucessfull'));
this.$modal.close('sucessfull');
that.$forceUpdate();
})
.catch((err) => {
global.loaderHide();
global.toast(err.message);
that.busy = false;
that.$forceUpdate();
});
}
当我循环数组并导入其中的每个项目时,问题发生了:this.dateList
forEach
this.dateList
this.dateList.forEach((date) => {
getLaborHed(
date,
this.user.employee.empId,
this.user.employee.shift
).then((res) => {
if (res) {
this.busy = false;
const data = JSON.parse(res.data.DataRaw);
if ((data || []).length > 0) {
dsLaborHed = dsLaborHed.map((el) => {
return {
...el,
ClockInDate: global.fsdate(date),
LaborHedSeq: data[0].LaborHed_LaborHedSeq,
};
});
dsLaborDtl = dsLaborDtl.map((el) => {
return {
...el,
ClockInDate: global.fsdate(date),
LaborHedSeq: data[0].LaborHed_LaborHedSeq,
ClockinTime: 0.0,
ClockOutTime: (23 * 1 + 59 / 60).toFixed(2),
DspClockInTime: '00:00',
DspClockOutTime: '23:59',
LaborHrs: parseFloat(laborHour3),
BurdenHrs: parseFloat(laborHour3),
};
});
} else {
dsLaborHed = dsLaborHed.map((el) => {
return {
...el,
ClockInDate: global.fsdate(date),
LaborHedSeq: 0,
};
});
dsLaborDtl = dsLaborDtl.map((el) => {
return {
...el,
ClockInDate: global.fsdate(date),
LaborHedSeq: 0,
ClockinTime: 0.0,
ClockOutTime: (23 * 1 + 59 / 60).toFixed(2),
DspClockInTime: '00:00',
DspClockOutTime: '23:59',
LaborHrs: parseFloat(laborHour3),
BurdenHrs: parseFloat(laborHour3),
};
});
}
console.trace(date);
this.importLaborDtl(dsLaborHed, dsLaborDtl); // Call async function importLaborDtl
} else {
this.busy = false;
}
});
});
它不能按顺序导入,有时它可以导入数组中的所有项目,有时它只是导入数组中的一些项目。我不确定这是否是异步问题。如果您能帮助我修复此错误,我将不胜感激。非常感谢。
答: 暂无答案
评论
importLaborDtl
不是异步的。了解如何使用 Promises。developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/......importLaborDtl
importLaborDtl
this.dateList
new Promise(...)
await