等待异步功能时可以设置变量值吗?

时间:2020-05-08 23:30:42

标签: javascript vue.js asynchronous

我有一个异步函数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

2 个答案:

答案 0 :(得分:2)

也许只是在await调用之前和之后设置变量?

this.IsUploading = true;

await fileUpload;

this.IsUploading = false;

答案 1 :(得分:1)

在某些情况下,您可以使用。

  1. 我认为这是最好,最正确的方法,它只会调用一次函数,也许问题出在另一件事上?
async submitForm() {
  const FormBody = new FormData();

  await fileUpload();

  this.$axios.post('/api', FormBody)
}
  1. 您可以将值设置为true,然后等到fileUpload()返回某些内容:
async submitForm() {
  const FormBody = new FormData();
  this.IsUploading = true;

  if (await fileUpload()) this.IsUploading = false;

  this.$axios.post('/api', FormBody)
}
  1. 或者在收到fileUpload()的回复后立即进行更改,如杰克·巴什福德说:
async submitForm() {
  const FormBody = new FormData();
  this.IsUploading = true;

  await fileUpload();
  this.IsUploading = false

  this.$axios.post('/api', FormBody)
}