Doubt when using a Query answer in Nodejs

Asked

Viewed 72 times

0

Well, first, I have two files: index.js that handles the requests and another that selects in the database, but I don’t know how to return it to the client.

app.get('/pesqAlimentos', (req, res) => {
    pesqAlimentos(req.query.pesq.barraPesq);        
});

The code above is from index.js.

function pesqAlimento(string){
    let str = string.toLowerCase().
    client.connect();
    client.query("SELECT * FROM pesquisaAlimentos('?')", [str]).then(res => 
    // aqui que não sei como retorno para o index as rows de 
    resposta para o index.js).catch(e => console.log(e))    
}

This is the file where select is done. What I wanted is to be able to return res.Rows, or be able to send it as an answer already.

1 answer

1


You already have a function that returns a promise, just use the await to unpack the result in this file, so you may not need callbacks and can simplify the code:

app.get('/pesqAlimentos', async (req, res) => {
    try {
        let rows = await pesqAlimentos(req.query.pesq.barraPesq);
        res.send(rows);
    } catch(err) {
        res.status(500).send(err);
    }      
});

async function pesqAlimento(string){
    let str = string.toLowerCase();
    client.connect();

    try {
        let res = await client.query("SELECT * FROM pesquisaAlimentos('?')", [str]);
        return res.rows;
    } finally {
        // Lembre de fechar a conexão. Um comando dentro do finally sempre 
        // irá rodar antes da função retornar ou lançar uma exceção
        client.close();
    }  
}

You will also need the modifier async in the functions they use await, if you’re not familiar with promises, inform yourself with the documentation here and here.

Browser other questions tagged

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