Manage function that may or may not return a promise [closed]

0



I have a function to which I send some parameters, and depending on those parameters makes a query in a BD or not.

The issue is that I need that if the query is made in the database the application waits for the query to finish to continue with the execution. For that I use promises.

The problem is that if a query is not made to the DB, the function code is not asynchronous, and it does not return a promise, so it gives me an error in the line where I call the function of the type:

TypeError: Cannot read property 'then' of undefined

In the event that a query to the BD is not made as I can do to return some kind of "false promise" and do not throw me this error?

    
asked by amblador 10.12.2018 в 23:57
source

2 answers

1

If you really want to return an empty promise you can do the following

return Promise.resolve(‘’) 
return Promise.resolve(null) 
return Promise.resolve() 

although the first returns a string empty the second null and the third undefined

your code would be the following

function hazalgo ( objeto={})
{
 if (objeto.algunapropiedad) {
    // algo
    return Promise.resolve();
} 

// llamado db

}

hazalgo({hola:'quetal'}).then()
    
answered by 13.12.2018 / 01:12
source
1

Does anything like this help you?

function revisarBaseDatos( objeto ) {
      return new Promise((resolve, reject) => {
        if (objeto.nombre === 'Akko') {
          // Es Akko, puede consultar la base de datos.
          resolve( "conectarBaseDatos()" );
          return;
        }
        // No es Akko, vamos a hacer operaciones y regresar un error
        let n = objeto.edad + 100;
        reject(n);
        return;
      });
  }
      let persona = { nombre: 'Akko', edad: 10000}
    revisarBaseDatos(persona).then((respuesta) => {
      // Se conectó a la base de datos.
      console.log(respuesta)
    }).catch((error) => {
      // No se conectó a la base de datos
    });

You have a function which returns a promise, a resolver handles the connection to the database and a reject handles the error.

You send to call the function and handle the possible error with a catch.

    
answered by 11.12.2018 в 00:33