Node JS - Function with Return does not pass data

Asked

Viewed 45 times

0

I’m trying to make a very basic API, to learn, but I can’t understand why the return of a function that takes data from BD does not return it to the other module.

I’m wearing Knex and ES6: This module (Controle) calls the function AtividadesTodas(), that is in the module models:

// Seleciona todas as atividades
    async todosRegs(req, res){
        var listaAtiv = await Atividades.AtividadesTodas();
        if(listaAtiv != undefined){
            res.json(listaAtiv);
        }else{
            console.log('lista vazia');
        }
        
    }

In the module Models, in this function, the data is stored in the variable data, so much that they can be displayed on the console, but apparently these data do not return, as it always falls on else, or is variable undefined:

 async AtividadesTodas(){
        await knex('Atividades').select('AtividadeDesc').orderBy('AtividadeDesc').then(data => {
            console.log(data);
            return data;
        }).catch(err => {
            console.log(err);            
        });

1 answer

3

The correct and used way is as follows by returning the Promise and in the resolve and bring the result, example:

AtividadesTodas() {
    return knex('Atividades').select('AtividadeDesc').orderBy('AtividadeDesc');
}

and in the :

async todosRegs(req, res) {
    try {
        const listaAtiv = await Atividades.AtividadesTodas();
        if(listaAtiv != undefined) {
            res.json(listaAtiv);
        } else {
            console.log('lista vazia');
        }   
    } catch (e) {
       // error
       console.log(e);
    }
}

Get a good read on that answer: When "Return" is different from "Return await" in an asynchronous function in Javascript?

  • 1

    Very good. And it seems that problem that many commit to mixing await with callback. Only one was missing try/catch to handle possible errors of AtividadesTodas.

  • Verdade @Cmtecardeal ...

  • 1

    Added @Cmtecardeal ...

  • 1

    It is worth remembering that in this case the return await is redundant (is the same as return). Refer to this other question.

  • So @luizfelipe until async is unnecessary?

  • 1

    If the function does not use await nowhere else (just returning the promise), it is not necessary not to. :-)

  • 1

    vlw @Luizfelipe pulled out and left returning only to builder to solve the promise out of

Show 2 more comments

Browser other questions tagged

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