【问题标题】:Angular 2 promise is not waiting to resolved nested promise?Angular 2 承诺不等待解决嵌套承诺?
【发布时间】:2017-04-04 11:10:32
【问题描述】:

在我的情况下,我必须在 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 [];
            });
        });
    }
}

【问题讨论】:

    标签: javascript cordova angular typescript ionic2


    【解决方案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 [];
             });
    }
    

    我真的相信连接到数据库不应该在这个地方完成,而是在一些常见的数据库服务上完成,这将是你的数据库层。理想情况下,当您调用此函数时,数据库应该已经连接/错误应该已经被抛出。因此,请花更多时间考虑架构。

    【讨论】:

    • 这个返回仍然不起作用,因为在第一个连接承诺中还有一个承诺存在,所以我猜这不会返回任何东西。 return 语句不会等待内部 promise 完成
    • @Sundar 只是了解有关承诺的更多信息。当.then 函数返回另一个promise 时,它​​会等到它被解析后再运行下一个.then
    【解决方案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 [];
        })
    }
    

    【讨论】:

      猜你喜欢
      • 2019-04-29
      • 2018-01-17
      • 1970-01-01
      • 2018-03-19
      • 1970-01-01
      • 2017-04-02
      • 2020-04-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多