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);
});
Very good. And it seems that problem that many commit to mixing
awaitwithcallback. Only one was missingtry/catchto handle possible errors ofAtividadesTodas.– Cmte Cardeal
Verdade @Cmtecardeal ...
– novic
Added @Cmtecardeal ...
– novic
It is worth remembering that in this case the
return awaitis redundant (is the same asreturn). Refer to this other question.– Luiz Felipe
So @luizfelipe until async is unnecessary?
– novic
If the function does not use
awaitnowhere else (just returning the promise), it is not necessary not to. :-)– Luiz Felipe
vlw @Luizfelipe pulled out and left returning only to
builderto solve thepromiseout of– novic