1

I am trying to write an service to get the list of customers but i don't know to return the list of customers from nested promose.

Please help me on this thanks in advance.

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 [];
            });
        });
    }
}
Sundar
  • 4,580
  • 6
  • 35
  • 61
  • What's the problem? Where and how do you call `getCustomerList()`? – Günter Zöchbauer Nov 19 '16 at 16:58
  • i don't know how to return the customers list `getCustomersList()` is this code has some issues inside the `getCustomersList()` i couldn't figure it out – Sundar Nov 19 '16 at 17:00
  • `return Promise.resolve(()=>{ ... })` resolves with a function, it doesn't call it. Is there a reason why it shouldn't be `return this.connect()...`? – Estus Flask Nov 19 '16 at 20:55
  • return statement is not waiting to resolve the promise. It's returns empty. How to make return statement wait – Sundar Nov 20 '16 at 05:03

1 Answers1

3

You need to chain the call with .then(...) like

this.getCustomerList().then(result => this.myArray = result);
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • can you clarify me only one thing is the `getCustomerList()` function is right – Sundar Nov 19 '16 at 17:04
  • `angular 2 return statement will wait for the promise to be completed` – Sundar Nov 20 '16 at 05:06
  • this question is related to this only http://stackoverflow.com/questions/37841721/angular2-wait-for-multiple-promises-to-finish . – Sundar Nov 20 '16 at 05:26