我有一个异步函数fileUpload()
,该函数将文件上传到服务器并在完成后返回一个Promise。当用户想要提交其他表单时,submitForm()
将在发布表单之前await fileUpload
。
在等待await fileUpload
的同时,我想告诉用户系统正在等待上传完成。这是我的想象(但显然无法正常工作):
async fileUpload() {
await Promise.all(
// Does a for loop here and uploads all files
)
}
async submitForm() {
const FormBody = new FormData();
await fileUpload; // I want to set this.IsUploading = true if awaiting. If not awaiting, then this.IsUploading = false;
this.$axios.post('/api', FormBody)
}
我使用await fileUpload
,但不带括号,因为如果执行await fileUpload()
,则它将再次调用该函数。但是,如果没有什么可等待的,我如何在等待this.IsUploading
完成的同时将true
设置为fileUpload()
,然后将其设置为false
?
答案 0 :(得分:2)
也许只是在await
调用之前和之后设置变量?
this.IsUploading = true;
await fileUpload;
this.IsUploading = false;
答案 1 :(得分:1)
在某些情况下,您可以使用。
async submitForm() {
const FormBody = new FormData();
await fileUpload();
this.$axios.post('/api', FormBody)
}
fileUpload()
返回某些内容:async submitForm() {
const FormBody = new FormData();
this.IsUploading = true;
if (await fileUpload()) this.IsUploading = false;
this.$axios.post('/api', FormBody)
}
fileUpload()
的回复后立即进行更改,如杰克·巴什福德说:async submitForm() {
const FormBody = new FormData();
this.IsUploading = true;
await fileUpload();
this.IsUploading = false
this.$axios.post('/api', FormBody)
}