javascript - Angular 2 的 promise 不等待嵌套 promise 解决吗?
在我的情况下,我必须在 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 [];
});
});
}
}
答案#1
你使用 Promise 的方式完全不自然。创建 Promise 是为了摆脱所谓的回调地狱。Promise 本应减少异步代码的复杂性,但你现在所做的恰恰是通向回调地狱的道路。
我稍微重写了你的函数,以便根据 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 [];
});
}
我真的相信连接数据库不应该在这个地方进行,而应该在一些公共的数据库服务中进行,这将是你的数据库层。理想情况下,当你调用这个函数时,数据库应该已经连接好/错误应该已经抛出。所以花更多时间考虑架构问题。
答案#2
你的方法 getCustomersList 应该返回一个 客户列表,还是返回一个查询 客户列表 的函数?如果是前者,那么这就是正确的做法:
getCustomersList(): Promise<any> {
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 [];
})
}
