Store result of promise in a variable

0

How can I store the promise result in a variable? A promise returns the result of a query of the database.

function consultaMarcas(){
    return new Promise(function(resolve, reject) {
      connection.query('SELECT * FROM marca',(err, result)=>{
        if(err) return reject (err);
        else return resolve(result);
      });
    });
  };
  var marcas = consultaMarcas().then(result =>{
  }).catch(err =>{
    console.log("ERRO: ",err);
  });

My problem is a little bigger, because I need to perform more than one query and I need to pass this to front as an example, here is what I would have on the server:

  function recebendoValoresBD() {
    Promise.all([
      consultaMarcas().then(),
      consultaTipos().then()
    ])
    .then(result =>{
      const marcas = {marca: result[0]};
      const tipos = {tipo: result[1]};
      res.render('marcas', marcas, tipos);
    })
    .catch(err =>{
      console.log("ERRO: ", err);
    });
  }

And here's the page

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Cadastro Modelo</title>
</head>
<br/>
            <h1>Cadastro Modelo</h1>
            <hr/>
            <form action="/modelos" method="post">
                Marcas:<SELECT NAME="ativo">
                        <option><%=marcas.marca[0].descricao%>
                        </SELECT>
                        <br>
                Tipos:<SELECT NAME="ativo">
                        <option><%=tipos.tipos[0].descricao%>
                        </SELECT>
                        <br>

                Descrição:<input type="text" name="descricao"/><br/>
                Ativo: <SELECT NAME="ativo">
                        <option>
                        <option>S
                        <option>N
                        </SELECT>
                        <button type="submit" class="btn btn-primary" >Proximo</button>
            </form>
        </body>
</html>

But doing so it returns me an error which is: TypeError: callback is not a function

    
asked by anonymous 23.07.2018 / 16:35

2 answers

1

You are already doing this. The value is inside the then in the result variable. Use what you need inside the Then.

function consultaMarcas(){
    return new Promise(function(resolve, reject) {
      connection.query('SELECT * FROM marca',(err, result)=>{
        if(err) return reject (err);
        else return resolve(result);
      });
    });
  };

  consultaMarcas().then(result =>{
   var marcas = result;
   console.log(marcas);
  }).catch(err =>{
    console.log("ERRO: ",err);
  });
    
23.07.2018 / 16:38
1

You can use the await statement to wait for the function to return:

...
// Funções assíncronas
let marcas = await consultaMarcas();

console.log(marcas);
...

Adding to the most complete example you gave:

async function resolver(req, res) {
  try {
    // Atribuição via desestruturação (destructuring assignment)
    let [marcas, tipos] = await Promise.all([consultaMarcas(), consultaTipos()]);

    // res.render(view [, locals] [, callback])
    res.render('marcas', {marcas, tipos});
  } catch(e) {
    console.error(e);
  }
}

In your route the call will look something like this:

router.get('/', resolver);
  

TypeError: callback is not a function

This error indicates that you are passing an object or other type of parameter to a function that expects a callback . According to the documentation for Express 4.x (which I assume you're using by the nomenclature of the parameters) the third parameter of the function render is an optional parameter destined to callback of the function:

  

res.render (view [ locals] [ callback])

     

Renders a view and sends the rendered HTML string to the client. Optional parameters:

     
  • locals , an object whose properties define local variables for the view.   
  • callback , the callback function. If provided, the method returns both the possible error and rendered string, but does not perform an automated response. When an error occurs, the method invokes next(err) internally.

  •   

Free translation:

  

Render the view and send the rendered HTML string to the client. Optional Parameters:

     
  • locals , an object whose properties define local variables for the view.

  •   
  • callback , a retribution function. If provided, the method returns both a possible error and the render string. When an error occurs, the method invokes' next (err) internally.

  •   

In view of the above explanation, replacing render with the following code should result in successful execution:

res.render('marcas', {marcas, tipos});
  

Asynchronous functions

     

The async function declaration defines an asynchronous function, which returns an object AsyncFunction .

     

You can also define asynchronous functions using a expression async function .

     

When an asynchronous function is called, it returns a Promise . When the asynchronous function returns a value, the Promise will be resolved with the returned value. When the asynchronous function throws an exception or some value, the Promise will be rejected with the value posted.

     

An asynchronous function may contain an expression await , which pauses the execution of the asynchronous function and waits for the resolution of the Promise passed, and then resumes execution of the asynchronous function and returns the resolved value.

  

Assignment via destructuring assignment

     

The destructuring assignment syntax is a JavaScript expression that makes it possible to extract data from arrays or objects into distinct variables.

    
23.07.2018 / 18:00