gpt4 book ai didi

javascript - 异步/等待上传任务

转载 作者:行者123 更新时间:2023-12-03 07:01:45 24 4
gpt4 key购买 nike

如何等待 uploadTask 以便我可以先上传图像/文件并跟踪其进度,然后再将下载 url dan 文档插入到 Firestore,

以下代码是我的示例 Vue 项目。它可以正常工作,但请参阅 if (portraitFile) ,必须在必须上传图片的条件下,不想上传图片怎么办?

它必须移出那个条件 if ,但它会在文件完成并检索到下载 URL 之前异步执行。

目标:将 firestore add() 移到uploadTask 的完成回调/参数之外。

    async commitCharacter() {
try {
let character = this.character;
let portraitFile = this.portraitFile;

if (portraitFile) {
const uploadTask = storageRef
.child(`characters/${character.id}/portrait.png`)
.put(portraitFile, { contentType: "image/png" });

await uploadTask.on(
"state_changed",
snapshot => {
this.portraitUploadProgress =
(snapshot.bytesTransferred / snapshot.totalBytes) * 100;
},
null,
async () => {
character.portraitUrl = await storageRef
.child(`characters/${character.id}/portrait.png`)
.getDownloadURL();

if (character.id) {
await db
.collection("characters")
.doc(character.id)
.update(character);
} else {
character.id = (await
db.collection("characters").add(character)).id;
}

$("#manageCharacter").modal("hide");
}
);
}
}

最佳答案

你可以把你的 uploadTask在 promise 中:

async function uploadTaskPromise() {
return new Promise(function(resolve, reject) {
const storageRef = storage.ref(YOUR_STORAGE_PATH)
const uploadTask = storageRef.put(YOUR_FILE_OR_BLOB)
uploadTask.on('state_changed',
function(snapshot) {
var progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100
console.log('Upload is ' + progress + '% done')
},
function error(err) {
console.log('error', err)
reject()
},
function complete() {
uploadTask.snapshot.ref.getDownloadURL().then(function(downloadURL) {
resolve(downloadURL)
})
}
)
})
}

然后像这样使用它:
const storageUrl = await uploadTaskPromise()
console.log(storageUrl) // do whatever you want with the URL...

关于javascript - 异步/等待上传任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53156127/

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