Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

357
Vistas
javascript - await doesn't wait

I am using Knex to do a simple select query from the database. I have returned a value in then function and added await before the async call. But await doesn't wait and always keep running next line with undefined value.

This is User model file with the console.log for the query result, this always get print last:

import knex from '../db/db.config.js';

const User = {};

User.findByNameAndPassword = (username, password) => {
  knex('user')
    .where({ name: username })
    .where({ password: password })
    .then(rows => {
      console.log(rows);
      return rows;
    })
    .catch((error) => {
      console.log(error);
    }) 
}

export default User;

and this is the controller, the console.log here is always printed first:

import User from '../models/user.js';

export const login = async (req, res) => {
  let name = req.body.name;
  let password = req.body.password;

  let user = await User.findByNameAndPassword(name, password)
    
  console.log('user', user);
}
over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

In order for await to work, you need to use it on a function that returns a promise, or a promise itself.

To do so in this instance, put return before knex('user') in your User.findByNameAndPassword function.

over 4 years ago · Santiago Trujillo Denunciar

0

Well, according to the code shared by you, it seems that findByNameAndPassword is a Synchronous Function. So awaiting will not help in controller. You might want to update your findByNameAndPassword to an Async one. Like this

import knex from '../db/db.config.js';

const User = {};

User.findByNameAndPassword = async (username, password) => {
    try {
        const rows = knex('user')
            .where({ name: username })
            .where({ password: password });
        console.log(rows);
        return rows;
    catch(err) {
        console.log(err);
    } 
}

export default User;

That should do it. What we are doing in this code is, we are trying to get the rows in the try block. And if it FAILS, the catch block will register an error and log the error for us.

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda