【发布时间】:2021-01-21 11:03:02
【问题描述】:
我一直在阅读并看到在 Promise 构造函数中使用 async/await 是一种反模式。
我当前的项目中有以下代码,我希望重构它,但不太确定我应该如何去做。
updateFileContentDownloaded(dataId: string[]): Promise<number> {
return new Promise(async (resolve, reject) => {
await this.db.initConnection2();
await this.db.connection2.openDb(dbName);
try {
const rows = await this.fileContentRepository.updateFileContent(dataId, this.db.connection2);
await this.db.connection2.terminate();
resolve(rows);
} catch (err) {
console.log('An error occur at get updateFileContentDownloaded method');
reject(err);
}
});
}
我尝试了以下方法,但在 finally 方法中出现错误
async updateFileContentDownloaded(dataId: string[]): Promise<number> {
await this.db.initConnection2();
await this.db.connection2.openDb(dbName);
return await this.fileContentRepository.updateFileContent(dataId, this.db.connection2).then((rows) =>
Promise.resolve(rows)
).catch(() =>
Promise.reject(0)
).finally(() => await this.db.connection2.terminate());
}
我正在为数据库使用 jsstore https://jsstore.net/tutorial/connection/
任何帮助将不胜感激。
谢谢。
【问题讨论】:
-
在 finally 调用中删除
await关键字。也只是return await this.fileContentRepository.updateFileContent(dataId, this.db.connection2).finnally...没有then和catch就足够了,因为你在处理程序内部没有做任何有用的事情
标签: angular promise anti-patterns