Promise waiting process finish to next process

I have a function that calls another function and I’m using promisse. Why does not the function wait for the other to finish to return the success (data)? It runs the date even before the loop (for) finishes it in the other function.

public cargaItens(){
      this.itensProcessados = "Processando...";
      this.webservice.carga(this.loja, this.dataitens, this.horaitens, this.servidor)
      .then(
        (data) => {
          this.itens = data.itens;
          return this.database.salvaCarga(this.itens)
          .then(
            (data) => { 
              this.itensProcessados = "Carga realizada com sucesso";
            },
            (error) => { 
              this.itensProcessados = "Erro ao fazer carga";
              this.database.presentToastError(JSON.stringify(error));
            }
          )
         },
        (error) => { 
          this.database.presentToastError(JSON.stringify(error));
         }
      )
   }

FUNCTION 2:

public salvaCarga(itens){
       return new Promise((resolve, reject) => {
        this.storage = new SQLite();
        this.storage.openDatabase({name: "infosysDB.db", location: "default"})
          .then(
            (data) => {
            for(let i=0;i<=itens.length-1;i++){
              let codigo = itens[i].codigo;
              this.storage.executeSql("SELECT codigo FROM itensoffline WHERE codigo = ?", [codigo])
              .then(
                (data) => {
                  let codigoitem = itens[i].codigo;
                  let descricao = itens[i].descricao;
                  let precodevenda = itens[i].precovenda;
                  let precoprazo = itens[i].precoprazo;
                  let precosugerido = itens[i].precosugerido;
                  let precoatacado = itens[i].precoatacado;
                  let precocma = itens[i].precocma;
                  let precocompra = itens[i].precocompra;
                  let estoque = itens[i].estoque;

                  if(data.rows.length > 0){
                      this.storage.executeSql("UPDATE itensoffline SET codigo = ?, descricao = ?, precodevenda = ?, "+
                                              "precoprazo = ?, precosugerido = ?, precoatacado = ?, precocma = ?, "+
                                              "precocompra = ?, estoque = ? WHERE codigo = ?", 
                                              [codigo, descricao, precodevenda, precoprazo, precosugerido, precoatacado, 
                                               precocma, precocompra, estoque, codigoitem])
                      .then(
                        (data) => {
                          // this.presentToastError(JSON.stringify(data));
                          resolve(data);
                        },
                        (error) => { 
                          this.presentToastError(JSON.stringify(error));
                          reject(error);
                        }
                      )
                    }else{
                      this.storage.executeSql("INSERT INTO itensoffline (codigo, descricao, precodevenda, precoprazo, precosugerido, precoatacado, precocma, precocompra, estoque) VALUES (?,?,?,?,?,?,?,?,?)", [codigo, descricao, precodevenda, precoprazo, precosugerido, precoatacado, precocma, precocompra, estoque])
                      .then(
                        (data) => {
                          // this.presentToastError(JSON.stringify(data) + " Insert");
                          resolve(data);
                        },
                        (error) => { 
                          this.presentToastError(JSON.stringify(error));
                          reject(error)
                        }
                      )
                    }
                }, 
                (error) => { 
                  this.presentToastError("Erro ao buscar item na tabela ITENS");
                  reject(error);
                }
              )
            }
            let mensagem = "Carga finalizada";
            resolve(mensagem);
          },
          (error) => {
            this.presentToastError("Erro ao abrir banco de dados.");
          });
      });
    }

Can anyone help me please ?

You’ve created callback hell, and Promises were introduced to avoid callback hell. Chain Promises, don’t nest them.

this.firstPromise().then(val1 => this.secondPromise())
                   .then(val2 => this.thirdPromise())

not

this.firstPromise().then(val => { this.secondPromise(); this.thirdPromise(); }

Simplify your code, type all your variables, and make sure you are chaining your async calls, not nesting them.

THIS IS ?

public salvaCarga(itens): any{
        this.storage = new SQLite();
        this.storage.openDatabase({name: "infosysDB.db", location: "default"})
        .then( data => "Banco de dados aberto com sucesso")
        this.storage.executeSql("SELECT * FROM itensoffline", [])
        .then( data => "SQL executado com sucesso")
}

The promises are working perfectly, I noticed that the problem is when the database executes the query, it continues executing the query that is to send 6000 items to the database, and the (data) gives me the answer before this query finishes

If you write code like

this.promise1().then(data => something);
this.promise2().then(data => somethingElse);

The promises will be executed in parallel, and your method will return before either of them is done. This is one reason you should never use any. If your method had return type Promise<string[]> (or whatever should actually be returned) the compiler would not have allowed you to make that mistake.

If you want data only when everything is completed, let’s say the data you want is an array of strings.

foo(): Promise<string[]> {
return this.promise1( usefulNameOfThingsFromPromise1 => doSomething)
    .then(_ => this.promise2() )
    .then( usefulNameOfThingsFromPromise2 => this.promiseThatReturnsArrayOfStrings());
}

Then you won’t see the array of strings until after Promises 1 and 2 are done.

Never use any. If you follow that rule, your life will become much easier.

I understand, but i try this and not work

public salvaCarga(itens): Promise<string[]>{
      return new Promise((resolve,reject) => {
        this.storage = new SQLite();
        this.storage.openDatabase({name: "infosysDB.db", location: "default"})
        .then(
          (data) => {
          for(let i=0;i<=itens.length-1;i++){
            let codigo = itens[i].codigo;
            let codigoitem = itens[i].codigo;
            let descricao = itens[i].descricao;
            let precodevenda = itens[i].precovenda;
            let precoprazo = itens[i].precoprazo;
            let precosugerido = itens[i].precosugerido;
            let precoatacado = itens[i].precoatacado;
            let precocma = itens[i].precocma;
            let precocompra = itens[i].precocompra;
            let estoque = itens[i].estoque;
            this.storage.executeSql("SELECT codigo FROM itensoffline WHERE codigo = ?", {codigo})
            .then(
              (data) => {
                if(data.rows.length > 0){
                    this.storage.executeSql("UPDATE itensoffline SET codigo = ?, descricao = ?, precodevenda = ?, "+
                                            "precoprazo = ?, precosugerido = ?, precoatacado = ?, precocma = ?, "+
                                            "precocompra = ?, estoque = ? WHERE codigo = ?", 
                                            [codigo, descricao, precodevenda, precoprazo, precosugerido, precoatacado, 
                                              precocma, precocompra, estoque, codigoitem])
                  }else{
                    this.storage.executeSql("INSERT INTO itensoffline (codigo, descricao, precodevenda, precoprazo, precosugerido, precoatacado, precocma, precocompra, estoque) VALUES (?,?,?,?,?,?,?,?,?)", [codigo, descricao, precodevenda, precoprazo, precosugerido, precoatacado, precocma, precocompra, estoque])
                  }
              }, 
              (error) => { 
                this.presentToastError("Erro ao buscar item na tabela itensoffline");
                reject(error)
              }
            )
          }
          resolve()
        },
        (error) => {
          this.presentToastError("Erro ao abrir banco de dados.");
          reject(error);
        })
      });
    }

You’re nesting a ton of Promises inside a Promise. That’s literally the first thing I told you not to do.

So how do you become my friend?

This is promise nesting too.

return this.promise1( usefulNameOfThingsFromPromise1 => doSomething)
.then(_ => this.promise2() )
.then( usefulNameOfThingsFromPromise2 => this.promiseThatReturnsArrayOfStrings());
}