gpt4 book ai didi

javascript - 如何等待Firebase存储图像上传,然后运行下一个函数

转载 作者:行者123 更新时间:2023-12-02 02:56:54 24 4
gpt4 key购买 nike

我正在尝试编写一个函数,将多个图像上传到 Firebase,保存返回到对象的网址,然后将该对象上传到我的 Cloud Firestore。我对异步/等待或 promise 并没有真正的理解,所以如果有人可以提供帮助,我将不胜感激。

基本上,我希望 uploadImages() 完成运行,然后运行 ​​uploadData(),其中 saveIssue() 在表单时被触发已提交。

这是我正在处理的内容:

saveIssue() {
this.uploadImages();
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() {
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);
},
complete: () => {
uploadTask.snapshot.ref.getDownloadURL().then(downloadURL => {
self.issue.images.push(downloadURL);
});
}
});
});
},

最佳答案

您必须使用 promise ,如所解释的 here 。您可以重写代码以支持异步等待,因为 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();
});
}
});
});
})
},

关于javascript - 如何等待Firebase存储图像上传,然后运行下一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60910131/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com