【问题标题】:Promise throws errorsPromise 抛出错误
【发布时间】:2017-11-23 18:44:05
【问题描述】:

我收到以下错误:

{"__zone_symbol__currentTask":{"type":"microTask","state":"notScheduled","source":"Promise.then","zone":"angular","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”。

【问题讨论】:

  • 您应该检查以确保事件没有被多次触发。

标签: typescript ionic-framework ionic3


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

【讨论】:

  • 我会将属性命名为 createdDb 而不是 db。所以它显示为this.createdDb.then(db =&gt; ...)
猜你喜欢
  • 1970-01-01
  • 2017-06-29
  • 2020-04-06
  • 2017-06-05
  • 2018-03-19
  • 2016-12-08
  • 1970-01-01
  • 2016-01-22
  • 2017-06-20
相关资源
最近更新 更多