承诺抛出错误

时间:2017-06-21 03:23:08

标签: typescript ionic-framework ionic3

我收到以下错误:

  

{ “__ zone_symbol__currentTask”:{ “类型”: “microTask”, “状态”: “notScheduled”, “源”: “Promise.then”, “区”: “角度”, “cancelFn”:NULL,” runCount“:0}}

我有一个类声明我正在调用一个返回Promise的方法....

export class TechPRODAO {
sqlite: any;
db: SQLiteObject;

constructor() {
    this.sqlite = new SQLiteMock();

    this.sqlite.create({
        name: 'techpro.db',
        location: 'default'
    }).then((_db: SQLiteObject) => {
        this.db = _db; 
    });
};

public executeSql(sqlstatement: string, parameters: any): Promise<any> {

    return this.db.executeSql(sqlstatement, parameters);
}

这是我拨打电话的地方

export class AppointmentDAO {
techprodao: TechPRODAO;

constructor(_techprodao: TechPRODAO) {
    this.techprodao = _techprodao;
};

public insertAppointment(appointment: Appointment) {
    console.log("insertAppointment called");
    this.techprodao.executeSql("INSERT INTO appointment (ticketnumber, customername, contactemail, contactphone, status, location, paymenttype, description, hascontract) " +
        "VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)", [appointment.ticketnumber, appointment.customername, appointment.contactemail, appointment.contactphone, appointment.status,
            appointment.location, appointment.paymenttype, appointment.description, appointment.hascontract])
        .then((data) => {
            console.log("Inserted into appointment: ticketnumber=" + appointment.ticketnumber);
        }, (error) => {
            console.log("ERROR in insertAppointment: " + JSON.stringify(error));
        });
}

insertAppointment会在executeSql上抛出错误,但我不明白为什么它没有正确地点击“then”。

1 个答案:

答案 0 :(得分:1)

作为一般规则,不要在构造函数中放置异步内容。你不知道他们什么时候准备好了。代替:

export class TechPRODAO {
  sqlite: any;
  db: Promise<SQLiteObject>;

  constructor() {
    this.sqlite = new SQLiteMock();

    this.db = this.sqlite.create({
      name: 'techpro.db',
      location: 'default'
    });
  }

  public executeSql(sqlstatement: string, parameters: any): Promise<any> {
    return this.db.then(db => executeSql(sqlstatement, parameters));
  }
}