如何在离子2/3中处理数据库异步操作 [英] How to handle database asynchronous operation in ionic 2/3

查看:122
本文介绍了如何在离子2/3中处理数据库异步操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用离子数据库,我调用一个API返回给我一些记录,我必须将这些记录插入数据库,何时插入操作已完成然后我想要从数据库中调用选择记录。问题是异步行为,在插入操作完成之前调用数据库中的选择记录。任何人都可以帮我解决这个问题吗?我的代码如下......

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

}

数据库插入和调用

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

我有多个INSERT我想在启动SELECT请求之前完成。我的问题是SELECT激活时INSERT尚未完成。

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.

推荐答案

中读取数据,然后方法:

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

这篇关于如何在离子2/3中处理数据库异步操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆