【发布时间】:2019-10-15 10:58:24
【问题描述】:
我需要在下一步逻辑之前为每个月创建文件,但是当我在 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:拉姆达 输入:{"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
【问题讨论】:
-
很抱歉我现在没有时间给出正确的答案,但你应该看看 Promise.all
标签: javascript typescript for-loop async-await