我需要在逻辑的下一步之前为每个月创建文件,但是当我在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函数之前,我创建了随机数量的文件。
日志:
NB-010:https://s3.com/avatars/image/01/s3list.txt
NB-010:https://s3.com/avatars/image/02/s3list.txt
NB-010:https://s3.com/avatars/image/03/s3list.txt
NB-010:https://s3.com/avatars/image/04/s3list.txt
NB-010:https://s3.com/avatars/image/05/s3list.txt
NB-010:https://s3.com/avatars/image/06/s3list.txt
NB-010:https://s3.com/avatars/image/07/s3list.txt
NB-010:https://s3.com/avatars/image/08/s3list.txt
NB-010:https://s3.com/avatars/image/09/s3list.txt
NB-010:https://s3.com/avatars/image/10/s3list.txt
NB-010:lambda
输入:{“ FunctionName”:“ filesCleanUp”,“ Payload”:“ {\” listName \“:\” avatars.txt \“}”}
NB-010:https://s3.com/avatars/image/11/s3list.txt
NB-010:https://s3.com/avatars/image/12/s3list.txt
最佳答案
如果将for循环转换为map,则可以使用Promise.all来解决
const promises = array.map(delayedLog);
// wait until all promises are resolved
await Promise.all(promises);