问题描述
我一直在阅读并看到在 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);
}
});
}
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/
任何帮助将不胜感激。
谢谢。
解决方法
正如我在上面的代码中看到的,连接在 try 中终止。可以重用它。您的代码的完整等效项应如下所示:
async updateFileContentDownloaded(dataId: string[]): Promise<number> {
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();
return rows;
} catch (err) {
console.log('An error occur at get updateFileContentDownloaded method');
throw err;
}
}
或者,如果你更喜欢 promises api 而不是 try catch 并且终止应该在 finally 块中,那么它就像
async updateFileContentDownloaded(dataId: string[]): Promise<number> {
await this.db.initConnection2();
await this.db.connection2.openDb(dbName);
return this.fileContentRepository.updateFileContent(dataId,this.db.connection2)
.finally(() => this.db.connection2.terminate())
}
,
正如@Andrei 建议的那样,您可以删除 new Promise
行并将 resolve
/reject
替换为 return
/throw
。但我想你真正想要的是使用 try
/finally
- 不要为此调用 promise 方法:
updateFileContentDownloaded(dataId: string[]): Promise<number> {
await this.db.initConnection2();
await this.db.connection2.openDb(dbName);
try {
return await this.fileContentRepository.updateFileContent(dataId,this.db.connection2);
} catch (err) {
console.log('An error occur at get updateFileContentDownloaded method');
throw err;
} finally {
await this.db.connection2.terminate();
}
}