【问题标题】:wait to promises inside for loop to end. Angular 7 / Typescript等待 for 循环内的 promise 结束。 Angular 7 / 打字稿
【发布时间】:2020-06-01 10:16:56
【问题描述】:

我正在使用 Angular 7,我有一个函数,它有一个承诺并将结果保存在这样的数组中:

appendImage(item){

this.imageCompress.compressFile(item, 50, 50).then(
  result => {
    this.compressedImages.push(result);
    return this.compressedImages;
  });

}

我正在从另一个具有 for 循环的函数中调用此函数/promise:

async compressFiles() {

if(this.elementsSelected.length > 0){
 for(let i = 0; i < this.elementsSelected.length; i++){
   let actual = this.elementsSelected[i].src;
   let res = await this.appendImage(actual);
   console.log(res);
 }

  return this.compressedImages;

}else{
  console.warn("No Images Selected");
}

}

当所有的 promise 调用结束时,我需要返回数组。当我从appendImage() 函数打印数组时,我得到了我想要的数组,但是执行console.log(res) 我得到undefined。 我做错了什么?

【问题讨论】:

    标签: angular typescript promise async-await


    【解决方案1】:

    为了正确等待你的函数,你需要返回承诺。

    appendImage(item){
    
    this.imageCompress.compressFile(item, 50, 50).then(
      result => {
        this.compressedImages.push(result);
        return this.compressedImages;
      });
    }
    

    应该是

    appendImage(item){
    // this is a promise, and you need to return it, in order to use await
    return this.imageCompress.compressFile(item, 50, 50).then(
      result => {
        this.compressedImages.push(result);
        return this.compressedImages;
      });
    }
    

    【讨论】:

      【解决方案2】:

      你不是从 appendImage 返回的。

      使用异步函数尝试以下操作。

      async appendImage(item) {
          const result = await this.imageCompress.compressFile(item, 50, 50);
          this.compressedImages.push(result);
          return this.compressedImages;
      }
      

      【讨论】:

        猜你喜欢
        • 2018-06-09
        • 2018-01-06
        • 2021-11-20
        • 2018-09-08
        • 2022-11-02
        • 1970-01-01
        • 2018-03-26
        相关资源
        最近更新 更多