业务需求,需要从一个接口中获取到一组数据,根据数据中的id去调取另一个接口得到最终的数据。
直接在for循环中调用axios在循环外得不到接口的数据:
getData() {
let data = [];
for (let i = 0; i < newArr.length; i++) {
let json = {
scheduleId: this.printForm.scheduleId,
colorId: newArr[i].colorId,
pCode: this.printForm.pcode,
spu: this.printForm.spu,
};
this.$api.productionProcess.findBarCode(json).then(res => {
data = data.concat(res.data);
});
}
console.log(data);
}
这样data = [],axios是异步调用,这时候需要用到async await来实现
async getData() {
let data = [];
for (let i = 0; i < newArr.length; i++) {
let json = {
scheduleId: this.printForm.scheduleId,
colorId: newArr[i].colorId,
pCode: this.printForm.pcode,
spu: this.printForm.spu,
};
let res = await this.$api.productionProcess.findBarCode(json);
data = data.concat(res.data);
}
console.log(data);
}
最终得到了想要的数据