javascript for循环内的异步调用

时间:2019-10-15 10:58:24

标签: javascript typescript for-loop async-await

我需要在逻辑的下一步之前每个月创建一个文件,但是当我在for循环中创建文件时,它不会等到此操作完成。

我试图将for循环带入单独的异步方法,该方法在主deleteAvatars方法中以“ await”调用。

private async s3ListsCreator(mainPathPart: string, type: string) {
    const promises = Constants.MONTHS_FOLDERS.map(async folder => {
      const s3Files: string[] = await this.getAllFiles(type, folder);
      try {
        await this.uploadS3FilesList(mainPathPart, s3Files, folder);
      } catch (err) {
        this.logger.error(err);
        return this.response
          .addError(new HttpErrors[400](`Upload on s3 list is unsuccessful`))
          .build();
      }
    });
    await Promise.all(promises);
}
 async deleteAvatars(): Promise<Response> {
try {
      await this.s3ListsCreator(fixPathPart, Constants.SUBFOLDERS.avatars);
    } catch (err) {
      this.logger.error(err);
      return this.response
        .addError(new HttpErrors[400](`Upload on s3 list is unsuccessful`))
        .build();
    }
try {
      await this.filesCleanUpLambdaCall(
        Constants.LIST_NAMES.avatarsList,
        avatarResolutions,
        Constants.SUBFOLDERS.avatars.concat(Constants.IMAGE, '/'),
      );
    } catch (err) {
      this.logger.error(err);
      return this.response
        .addError(new HttpErrors[400](`Clean up is unsuccessful`))
        .build();
    }
}

我需要在lambda调用之前创建所有文件,但是在调用lambda函数之前,我创建了随机数量的文件。

日志:

1 个答案:

答案 0 :(得分:1)

如果将for循环转换为map,则可以使用Promise.all来解决

const promises = array.map(delayedLog);
// wait until all promises are resolved
await Promise.all(promises);