Synchronous query in SQLite using Ionic

2

I have the following function below:

public requisicaoXPTA() {
  this.database.executeSql("SELECT * FROM tbl_xpta",
      []).then((data) => {
      // o resultado retorna aqu na variável data

      }, (error) => {
        console.log(error);    
  });
}

When I use this function I do this:

this.requisicaoXPTA();
this.atualizar();

Most of the time, the atualizar() function is executed before requisicaoXPTA() . I would like to execute the atualizar() function after having made the request in the table. What better way to do this synchronously?

    
asked by anonymous 01.12.2017 / 16:24

3 answers

1

You can pass a callback to run after the request, like this:

public requisicaoXPTA(callback) {
  this.database.executeSql("SELECT * FROM tbl_xpta", []).then((data) => {
    callback();
  }, (error) => {
    console.log(error);    
  });
}

The use would look like this

this.requisicaoXPTA(this.atualizar);
    
04.12.2017 / 20:30
1

I could use the idea of @LINQ, but made the callback optional:

public requisicaoXPTA(callback) {
  this.database.executeSql("SELECT * FROM tbl_xpta", []).then((data) => {
    if (callback) callback(data);
  }, (error) => {
    console.log(error);    
  });
}

At the moment you need this.atualiza , you would use this:

requisicaoXPTA(this.atualiza);

When not in use just omit:

requisicaoXPTA();

Or you could use a parameter to tell when to upgrade, for example:

public requisicaoXPTA(refresh) {

  this.database.executeSql("SELECT * FROM tbl_xpta", []).then((data) => {
    if (refresh) this.atualiza(data);
  }, (error) => {
    console.log(error);    
  });
}

I do not remember if this works within => {} due to scope if it does not do so:

public requisicaoXPTA(refresh) {
  var callback = refresh ? this.atualiza : false;

  this.database.executeSql("SELECT * FROM tbl_xpta", []).then((data) => {
    if (callback) callback();
  }, (error) => {
    console.log(error);    
  });
}
    
05.12.2017 / 04:34
0

You can use async and await that is present since typeScript 2.1 .

Example:

public async requisicaoXPTA() {
    return new Promise((resolve, reject) => {
      this.database.executeSql("SELECT * FROM tbl_xpta",
        []).then((data) => {
          resolve(data);
        }, (error) => {
          reject(error);
        });
    })
}

Notice that I'm solving the promise so we can get the result out of it. You can do this by calling your function:

let resultado = await this.requisicaoXPTA();

With await the promisse will be resolved and 'cursor' will be locked in this function until it is complete. Next you can call your other function:

let resultado = await this.requisicaoXPTA();
console.log(resultado);
this.atualizar();
    
05.12.2017 / 13:05