就我而言,我必须获取 customerService 上的客户列表并返回到组件。请任何人都可以帮助我重写 getCustomersList 方法。
import { Injectable } from '@angular/core';
import { SQLite } from 'ionic-native';
@Injectable()
export class CustomerService {
private sDBName:string;
private db;
private isDBExist:boolean = false;
constructor() {}
setDBName(sDBName:string) {
this.sDBName = sDBName;
}
connect():Promise<any> {
this.db = new SQLite();
return this.db.openDatabase({
name: this.sDBName,
location: 'default'
});
}
getCustomersList():Promise<any> {
return Promise.resolve(()=>{
return this.connect().then(()=>{
this.isDBExist = true;
let sql = 'SELECT * FROM customer ORDER BY customer_id DESC LIMIT 10';
return this.db.executeSql(sql, {}).then((result)=>{
let customers = [];
for(let i=0; i<result.rows.length; i++) {
customers.push(result.rows.item(i));
}
return customers;
},(err)=>{
this.debug('Unable to select customers', err);
return [];
});
},(err)=>{
this.debug('Unable to open database', err);
return [];
});
});
}
}
最佳答案
你以一种绝对不自然的方式使用 Promise。 Promise 的创建是为了摆脱所谓的回调 hell 。 Promise 应该会降低异步代码的复杂性,但你所做的正是通往回调 hell 的道路。
我稍微重写了你的函数,以便根据 Promise 标准工作。这可能不是一个开箱即用的解决方案,但您没有向我们提供任何 plunker,所以这只是一个概念:
getCustomersList(): Promise<any> {
return this.connect()
.catch(err => throw new Error('Unable to open database', err))
.then(() => {
this.isDBExist = true;
return this.db.executeSql('SELECT * FROM customer ORDER BY customer_id DESC LIMIT 10', {})
})
.catch('cannot execute query')
.then(result => result.rows.map(row => row.item(i)))
.catch(err => {
this.debug('Unable to select customers', err);
return [];
});
}
我真的相信与数据库的连接不应该在这个地方完成,而应该在一些公共(public)数据库服务上完成,这将是您的数据库层。理想情况下,当您调用此函数时,数据库应该已经连接/应该已经抛出错误。所以花更多的时间去思考架构。
关于javascript - Angular 2 Promise 不是在等待解决嵌套 Promise 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40713691/