Store Promise output in a variable

Asked

Viewed 2,968 times

0

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

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 that is: Typeerror: callback is not a Function

  • Has any response helped solve the problem and can address similar questions from other users? If so, make sure to mark the answer as accepted. To do this just click on the left side of it (below the indicator of up and down votes).

2 answers

1

You are already doing this. The value is inside the then in the variable result. Use what you need inside 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);
  });
  • 1

    Thank you, and how can I use this variable later?

  • @victor_bez you can make your logic inside Then if you just return the Rest result for example or you can return the tag value. var tags = query Marks(). then(result =>{ Return result; }). catch(err =>{ console.log("ERROR: ",err); });

  • @victor_bez in case if only to return the response to the request inside then could do query(). then(result =>{ Return res.json(result); }). catch(err =>{ console.log("ERROR: ",err); })

  • 1

    Thanks for the attention, I discovered what was wrong res.render('models', {marks, types}) this would be the correct form, in the documentation asks for a third parameter which is a callback;

1

You can use the instruction await to await the return of the function:

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

console.log(marcas);
...

Adding to the most complete example you have given:

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);
  }
}

On your route the call will look like the following:

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 of Express 4.x (which I deduce that you are using by the parameters nomenclature) the third parameter of the function render is an optional parameter for callback of 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, a 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.

In free translation:

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

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

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

In view of the above explanation the replacement of render for the following code shall result in successful execution:

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

Asynchronous functions

The statement async Function defines an asynchronous function, which returns an object Asyncfunction.

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

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

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 the execution of the asynchronous function and returns the solved value.


Assignment via structuring (destructuring assignment)

The syntax of assignment via structuring (destructuring assignment) is an expression JavaScript that makes it possible to extract data from arrays or objects in different variables.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.