2 回答
TA贡献1802条经验 获得超10个赞
您必须使用承诺,如此处所述。你可以重写你的代码来支持异步等待,因为firebase支持它开箱即用,但一开始它可以是这样的:
async saveIssue() {
await this.uploadImages();
await this.uploadData();
},
uploadData() {
return new Promise((resolve, reject) => {
let self = this;
db.collection("issues")
.add(self.issue)
.then(docRef => {
self.$router.push({
name: "ReportPage",
params: {
issueId: docRef.id
}
});
resolve();
})
.catch(error => {
console.error(error);
reject(error);
});
})
},
uploadImages() {
return new Promise((resolve, reject) => {
const storageRef = storage.ref();
let self = this;
this.imagePreviews.forEach(image => {
let imageName = uuidv1();
let fileExt = image.fileName.split(".").pop();
let uploadTask = storageRef
.child(`images/${imageName}.${fileExt}`)
.putString(image.base64String, "data_url");
uploadTask.on("state_changed", {
error: error => {
console.error(error);
reject(error);
},
complete: () => {
uploadTask.snapshot.ref.getDownloadURL().then(downloadURL => {
self.issue.images.push(downloadURL);
resolve();
});
}
});
});
})
},
TA贡献1812条经验 获得超5个赞
好的,我根据@AlexBrohshtut 的回答找到了一个解决方案。我仍然有一个问题,即第一个循环完成将允许等待继续,下面的代码似乎解决了这个问题。如果有人有更简洁的答案,很高兴更新!(我充其量是中级...)
saveIssue() {
Promise.all(
this.imagePreviews.map(async image => {
return await this.uploadImages(image);
})
).then(() => {
this.uploadData();
});
},
uploadData() {
let self = this;
db.collection("issues")
.add(self.issue)
.then(docRef => {
self.$router.push({
name: "ReportPage",
params: {
issueId: docRef.id
}
});
})
.catch(error => {
console.error(error);
});
},
uploadImages(image) {
const storageRef = storage.ref();
let self = this;
return new Promise((resolve, reject) => {
let imageName = uuidv1();
let fileExt = image.fileName.split(".").pop();
let uploadTask = storageRef
.child(`images/${imageName}.${fileExt}`)
.putString(image.base64String, "data_url");
uploadTask.on("state_changed", {
error: error => {
console.error(error);
reject(error);
},
complete: () => {
uploadTask.snapshot.ref.getDownloadURL().then(downloadURL => {
self.issue.images.push(downloadURL);
resolve();
});
}
});
});
}
添加回答
举报