2016-11-21 151 views
2

在我的情况下,我必须获取customerService上的客户列表并返回到组件。请任何人都可以通过重写getCustomersList方法来帮助我。Angular 2承诺不等待解决嵌套承诺?

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 []; 
      }); 
     }); 
    } 
} 

回答

3

你以绝对不自然的方式使用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 []; 
     }); 
} 

我真的beleive连接到数据库不应在此进行但是在一些常见的数据库服务中,这将是您的数据库层。理想情况下,当你调用这个函数时,数据库应该已经被连接了/错误应该已经被抛出。所以花更多的时间去思考这个架构。

+0

这个回报仍然不会工作,因为在第一个连接的承诺之内还有一个承诺存在,所以这将不会返回任何我猜。 return语句不会等待内部承诺完成 – Sundar

+1

@Sundar只是更多地了解承诺。当'.then'函数返回另一个承诺时,它会等到它解析后再运行下一个'.then' – smnbbrv

1

如果你的方法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 []; 
    }) 
}