调用函数时异步等待不起作用

时间:2021-03-17 08:18:00

标签: angularjs typescript ionic-framework angular-promise

var value = await this.upload();
if (value == true) {
  this.item.photos = this.uploaded;
  this.item.price = null;
  this.item.qty = null;
  this.dataSrv.addItem(this.item)
    .then(() => {
      this.dataSrv.stopLoading();
      this.dataSrv.toast('Item Added Successfully');
      this.item = {} as Item;
      this.pictures = ['', '', '', ''];
      this.uploaded = [];
      this.photos = ['', '', '', ''];
    })
    .catch(err => {
      this.dataSrv.stopLoading();
      this.dataSrv.toast('Error While Adding Item. Try Again Later');
      console.log(err);
    });
}

在上面的代码中,我正在调用上传功能将图片上传到谷歌存储,我正在等待,所以我可以将图像链接添加到上传的数组中,这将保存到 this.item.photos 但它不等待,它直接执行真条件。

async upload(image?) {
  var counter = 0;
  this.pictures.forEach(i => {
    if (i != '') {
      let temp: string = (i) as string;
      temp = temp.replace("data:image/jpg;base64, ", '');
      temp = temp.replace("data:image/jpg;base64,", '');
      temp = temp.replace('must use [property]=binding:', '');
      temp = temp.replace('SafeValue', '');
      temp = temp.replace('(see https://g.co/ng/security#xss)', '');
      const randomId = Math.random().toString(36) + Math.random().toString(36) + Math.random().toString(36) + Math.random().toString(36);
      const uploadTask = this.storage.ref('items/').child(randomId).putString(temp, 'base64', {
        contentType: 'image/png'
      });
      uploadTask
        .then(response => {
          console.log("uploaded");
          console.log(response);
          this.storage.ref('items/' + randomId).getDownloadURL().subscribe(url => {
            this.uploaded.push(url);
            counter++;
          });
        })
        .catch(err => {
          console.log('not uploaded');
        });
    }
  });
  if (counter != this.uploaded.length) {
    return false;
  } else {
    return true;
  }
}

我尝试在上传函数中做返回类型的 Promise 但没有任何改变 我也试过在函数调用之后做 then 但同样的问题发生了

注意图片数组包含base64图像

1 个答案:

答案 0 :(得分:2)

async 函数不会自己阻塞。问题是 forEach 被同步调用,但它包含将异步运行的代码。

执行此操作的常见模式:

async upload(image) {
  // use .map instead of .forEach
  // from the callback function we return a Promise, so the result would be
  // an array of promises
  const promises = this.pictures.map(i => {
    // your logic here
    // you must return the promise
    return uploadTask
        .then(response => { /* ... */ })
        .catch(() => { /* ... */ });
  })

  // Wait for all promises to be resolved.
  // Note for the future: Promise.all will reject if at least 1 promise rejects.
  // Your code seems to handle this case and converts a failed Promise into a success inside of `.catch` above.
  await Promise.all(promises);

  // here, the counter should be correct
}