【问题标题】:How to handle database asynchronous operation in ionic 2/3如何在 ionic 2/3 中处理数据库异步操作
【发布时间】:2018-07-18 21:59:31
【问题描述】:

我正在使用 ionic 中的数据库,我调用了一个返回许多记录的 API,我必须将这些记录插入数据库以及何时完成插入操作然后我想要从数据库中调用选择记录。问题是异步行为,在插入操作完成之前调用数据库中的选择记录。谁能帮我解决这个问题?我的代码在下面...

数据库提供者:

export class DbProvider {


  public addData(dId: string, sId: string, subId: string, subName: string,
    dDate: string, cId: string, cName: string, stdId: string, stdName: string,
  ) {
    return new Promise((resolve, reject) => {
      this.db.executeSql("INSERT INTO data (dId , sId , subId , subName ," +
        " dDate , cId , cName , stdId , stdName ) VALUES (?, ?,?, ?,?, ?,?, ?,?)",
        [dId, sId, subId, subName, dDate, cId, cName, stdId, stdName]).then((data) => {
          resolve(data);
        }, (error) => {
          reject(error.tostring());
        });
    });
  }

}

数据库插入和调用

for (let temp of ApiData) {

  this.DbHandler.IsAvailable(temp.dId).then(data => {


    if (data) {
      console.log("did Available editing " + data);

      this.DbHandler.editData(temp.dId, temp.sId, temp.subId, temp.subName,
        temp.dDate, temp.cId, temp.cName);


    } else {
      console.log("did not Available inserting " + data);

      this.DbHandler.addData(temp.dId, temp.sId, temp.subId, temp.subName,
        temp.dDate, temp.cId, temp.cName);

    }
  });
}

this.getDataFromDb();

在开始 SELECT 请求之前,我想完成多个 INSERT。我的问题是 SELECT 触发时 INSERT 尚未完成。

【问题讨论】:

    标签: database sqlite ionic-framework ionic2 ionic3


    【解决方案1】:

    then方法中调用从DB读取:

    let promises = [];
    for (let temp of ApiData) {
      let promise = new Promise((resolve, reject) => {
        this.DbHandler.IsAvailable(temp.dId).then(data => {
          if (data) {
            console.log("did Available editing " + data);
            this.DbHandler.editData(temp.dId, temp.sId, temp.subId, temp.subName,
              temp.dDate, temp.cId, temp.cName).then(() => resolve());
          } else {
            console.log("did not Available inserting " + data);
            this.DbHandler.addData(temp.dId, temp.sId, temp.subId, temp.subName,
              temp.dDate, temp.cId, temp.cName).then(() => resolve());
          }
        });
      };
      promises.push(promise);
    }
    Promise.all(promises).then(() => this.getDataFromDb());
    

    【讨论】:

    • 我想在循环中完成所有插入操作后调用 this.getDataFromDb()
    猜你喜欢
    • 2015-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-05
    • 2019-10-16
    • 2021-11-28
    • 2018-07-21
    相关资源
    最近更新 更多