Ionic 承诺在爱奥尼亚语中是没有回报的

tsm1rwdh  于 9个月前  发布在  Ionic
关注(0)|答案(1)|浏览(131)

myService中的getNameFromDB()返回一个promise。当我从home.page.ts调用此函数时,promise没有返回。我检查了关于SO的不同建议,但没有一个可以解决此问题。以下是我的代码:
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表示myService中的getNameFromDB(),并且应返回resolve('success');,但未显示home.page.ts中的三个日志。
在我看来,承诺是没有返回,因为既没有在then中的日志,也没有在catch中的日志显示!

piah890a

piah890a1#

这不是一个离子问题,而是一个一般的TS/JS问题。你不应该使用return new Promise(),而应该使用try/catch和aprc/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);
}

相关问题