SQLStorage and ordered promises/returns


#1

Im using SqlStorage in my app and its working well. However, I am having issues with ordering my DB calls. The transactions are performed as promises, but I need to order them sequentially using .then, to avoid doing INSERTS in tables that do not exist yet. E.g.

The process flow I am aiming for is as follows:

  1. App launches.
  2. Platform.ready() returns.
  3. Check database for tables. If not exist, create tables.
  4. After all tables are created, populate with data from pre-loaded JSON.

I have isolated and tested my code for each function and they all work. My issue, however, is ensuring that the tables are created BEFORE the JSON is parsed.

My method is as follows:

app.js

   db.initialiseTables().then(() => {
        db.preloadFactoryShipped()
      });

db-helper.js

initialiseTables() {
    console.log('--Initialise Tables--');
    return this.createPeopleTable()
      .then(() => {
        this.createSpeakersTable()
      })
      .then(() => {
        this.createMapTable()
      });
  }

preloadFactoryShipped() {
    console.log('Loading Factory Data');
    //load factory shipped data
    this.http.get('data/data.json').subscribe(res => {
      this.data = this.saveToDatabase(res.json());
    });
  }

  createPeopleTable() {
    return this.storage.query("CREATE TABLE IF NOT EXISTS people (id INTEGER PRIMARY KEY AUTOINCREMENT, firstname TEXT, lastname TEXT)").then((data) => {
      if (data.res.insertId == 0) {
        console.log('-- SQL: People Table: Already Exists');
      } else {
        console.log('-- SQL: Peoples Table: Created New');
      }
    }, (error) => {
      console.log('ERROR -> ' + error.err.message);
    });
  }

  createSpeakersTable() {
    **sameFormat as createPeopleTable**
  }

My issue is that the call I use in app.js to initialiseTables().then(…) seems to not wait for the initial method to return the chain of promises once they are complete. Can someone help me. I have messed around for hours with these promises.


#2

Still struggling with this one. Any fresh ideas as to where I’m going wrong?


#3

Because you use Promise inside another Promise. Of course, it isn’t synchronized.


#4

I thought thats how you chain promises, so they perform sequentially?


#5

Yes. But this then method is of first promise

db.initialiseTables().then(() => {
  db.preloadFactoryShipped()
})

#6

Assuming the tables don’t have any dependencies (like foreign key constraints), you could refactor initialiseTables like so:

initialiseTables() {
  console.log('--Initialise Tables--');
  return Promise.all([
    this.createPeopleTable(),
    this.createSpeakersTable(),
    this.createMapTable()
  ]);
}

#7

@rapropos Sorry for the delay in replying. Thank you very much for your help with this. Works perfectly. Obviously I need more time working with promises.