How to handle database asynchronous operation in ionic 2/3

让人想犯罪 __ 提交于 2019-12-24 01:59:06

问题


I am working with the database in ionic, I call one API that returns me a number of records, I have to insert those records into the database and when to insert operations are completed then I want to call select records from the database. problem is asynchronous behavior, the select records from the database called before the insert operations are completed. can anyone help me to resolve this? my code is below...

DbProvider:

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());
        });
    });
  }

}

database insert and call

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();

I have multiple INSERTs I'd like to be done before starting SELECT requests. My problem is that the INSERT is not yet finished when the SELECT fires.


回答1:


Call read from DB in then method:

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());


来源:https://stackoverflow.com/questions/48683679/how-to-handle-database-asynchronous-operation-in-ionic-2-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!