getNameFromDB()
返回一个承诺。当我从 home.page.ts
调用此函数时,不会返回承诺。我检查过不同的建议,但没有一个能解决问题。这是我的代码:
myService.ts:
public getNameFromDB(){
return new Promise((resolve, reject) => {
let param = {
table: "info",
columns: "*",
where: "id=1"
};
this.dbService.select(param).then(
(res: []) => {
if (res.length != 0)
if (res[0]['name'] != '')
this.nameIsSet = true;
console.log('Name is set? ', this.nameIsSet);
resolve('success');
},
(err) => {
console.error('Error while reading info: ', err);
reject(err);
}
).catch(e => {
console.error('[myService.ts] catch error: ' + e);
reject(err);
});
}) // close promise
} //close function
home.page.ts:
this.myService.getNameFromDB().then(
(res)=>{ console.log('1. Name is set.')},
(err)=>{ console.log('2. Some error.')}
)
.catch(e => {
console.error('3. catch error: ' + e);
});
代码的行为是什么?在控制台中我可以看到:
name is set? true
表示 getNameFromDB()
中的 myService
,已执行并应返回 resolve('success');
,但 home.page.ts
中的三个日志均未显示。
在我看来,承诺没有返回,因为既没有登录
then
,也没有显示登录catch
!
这不是一个离子问题,而是一个一般的 TS/JS 问题。您不应该使用
return new Promise()
,而应使用 try/catch 和 async/await。
public async getNameFromDB() {
try {
const param = {
table: "info",
columns: "*",
where: "id=1"
};
const res: [] = await this.dbService.select(param);
if (res.length > 0 && res[0]['name'] !== '') {
this.nameIsSet = true;
}
console.log('Name is set? ', this.nameIsSet);
return 'success';
} catch (err) {
console.error('Error while reading info: ', err);
throw err;
}
}
然后致电:
try {
const res = await this.myService.getNameFromDB();
console.log('1. Name is set.');
} catch (err) {
console.error('2. Some error: ' + err);
}