How to correctly perform a function that returns a promise with Ionic?

1

I want to do a function that gives me back a promise, but I do not really understand the subject, what I tried is this

MiFuncion(miParametro: string): Promise<void>{
    // mi codigo ...
    console.log(miParametro)
    return new Promise (function( resolve, reject){
        resolve()
     })
 }
this.MiFuncion('Probando').then(()=>console.log('esto funciono corretamente')).catch((err)=>console.log(err))

Would this be okay?

    
asked by Daniel Enrique Rodriguez Caste 18.10.2017 в 00:05
source

2 answers

0

You must include all the code (or at least the asynchronous code for which you need to use a promise) within the parameter function of your promise. I imagine that in ionic context it would be something like this:

@Component({..})
export class FooComponent implements OnInit {

  ngOnInit() {
    this.miFuncion('hola', 'mundo').then(..);
  }

  miFuncion(param1, param2): Promise<any> {

    /** 
     * Fíjate que acá debes usar un lambda en vez de una función
     * anónima, de lo contrario el contexto de 'this' va a ser el de la 
     * función que le pasas a Promise, y no el 'this' de FooComponent 
     */
    return new Promise((resolve, reject) => {
      /** 
       * En este caso, obtengo el resultado de otra función para usarlo
       * dentro del cuerpo de mi promesa
       */
      const saludo = this.miOtraFuncion(param1, param2);

      if ( saludo === 'hola mundo' ) {
        /**
         * 'Hola mundo que hace' es entonces el valor que va a recibir
         * el primer callback en .then(), en caso de que se cumpla 
         * la condición
         */
        resolve('Hola mundo que hace');
      } else {
        /**
         * Este mensaje irá en el segundo callback de .then, o bien
         * puedes capturarlo al final con .catch()
         */
        reject('Mal educado');
      }
    });
  }

  miOtraFuncion(param1, param2): string {
    // realiza algún proceso
    return param1 + " " + param2;
  }
}

Let's see now how you can chain promises and the general behavior of then() and catch() :

@Component({..})
export class FooComponent implements OnInit {

  ngOnInit() {
    this.miFuncion('hola', 'mundo').then(
      // El primer callback se ejecuta si la promesa fue resuelta con resolve()
      (success_msg) => {
        /** 
         * Lo bueno de las promesas, es que si retornas cualquier valor
         * dentro de uno de sus callbacks, puedes seguir encadenando
         * promesas con then()
         */
        console.log(success_msg); // "Hola mundo que hace"
        return this.servicio.getAlgo(); 
      },
      // El segundo callback se ejecuta si la promesa fue resuelta con reject() 
      (error_msg) => console.log(error_msg); // "Mal educado"
    )
    .then(
      (data) => {
        // el valor de data lo que retorna la llamada a this.servicio.getAlgo()
        return "kittenRequest";
      }
    )
    .then(
      (value) => console.log(value); // "kittenRequest"
    )
    .catch(
      // En .catch() vas a capturar cualquier error que haya salido en la cadena 
      // de promesas de no haber sido manejado por el segundo callback de then
      (error) => {
        // Haz algo con el error
      }
    )
  }
}

As you can see, once inside a chain of promises, you can orchestrate the sequence of processes in the order you want.

If you want to learn more about it, I recommend the following free NodeSchool workshop although it is in English as you can see, Promise It Will not Hurt

    
answered by 22.10.2017 / 11:46
source
0

I do not understand your question very well since I do not see the need to return a promise as a result, I rather believe that in your case what you want to do is to be able to sequence several promises to achieve certain behavior in sequence. If that is your objective what you could try to create all the promises and then send them to run in a chain, I'll try to illustrate, it will be something like this:

var prom1 = Prom1(req, res).then(function(resul1) {
        Prom3(req, res).then(function(resul2){
            Prom3(req, res).then( function (resul3) {
                if (resul3) {
                    ProcesarAlgo(resul3);
                } else {
                    console.log("paso algo");
                }               
            })
        }); 
    }).catch( function (errorDB) {
        console.log("------------------------ERROR------------------");
    });

Within the then of each promise you can retrieve a value that is either a set of data or a boolean type that you can send for the next promise or process it in the way you prefer with either if or what you need. I hope I have helped you, regards.

    
answered by 18.10.2017 в 06:33