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

290
Vistas
How to wait for API response in separate function before continuing execution?

I'm new to JavaScript/NodeJS and am having a hard time understanding what is going on here. I'm writing a function that will perform some action based on the response of an API post request within a separate function. For now, that action is just displaying a message on failure or success.

The below code (inside an app.js file) is simply meant to grab the user inputs, pass them to the login_user function (inside an authenticate.js file), and display a message based on the response from login_user.

const { login_user } = require('./authenticate');
// Other requirements
// App initialization

app.post('/auth', function (req, res) {
    let username = req.body.username;
    let password = req.body.password;

    let response = login_user(username, password);
    if (response == 204) {
        res.send("Success");
    } else {
        res.send("Failure");
    }
});

The below code (inside authenticate.js) accepts the user input, makes an API call, and returns the status code for the response.

const axios = require('axios');
const querystring = require('querystring');

function login_user(username, password) {
    var data = {
        j_username: username,
        j_password: password
    };

    axios.post("https://fakeurl.com", querystring.stringify(data))
    .then(function (response) {
        return response.status;
    })
    .catch(function (error) {
        return response.status;
    });
}

module.exports = {
    login_user
}

What happens is, once the login_user function is called, the code continues executing and goes straight to the else clause of the if/else statement, always resulting in a failure. I would like to wait for the response to be returned before executing the if/else statement.

I tried using async/await with this configuration...

app.post('/auth', async function (req, res) {
    let username = req.body.username;
    let password = req.body.password;

    let response = await login_user(username, password);
    if (response == 204) {
        res.send("Success");
    } else {
        res.send("Failure");
    }
});

...but did not have any luck. Did I do this incorrectly?

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Try this,

const services = require('./authenticate');

app.post('/auth', async function (req, res) {
    try {
        let username = req.body.username;
        let password = req.body.password;

        let response = await services.login_user(username, password);

        if (response == 204) {
            res.send("Success");
        } else {
            res.send("Failure");
        }
    } catch (e) {
        return res.status(500).json({ status: 500, message: e.message });
    }
});

And,

Inside authenticate.js file

const axios = require('axios');
const querystring = require('querystring');

exports.login_user = async function (username, password) {

    try {
        let data = {
            j_username: username,
            j_password: password
        };

        return axios.post("https://fakeurl.com"`enter code here`, querystring.stringify(data))
            .then(function (response) {
                return response.status;
            })
            .catch(function (error) {
                return response.status;
            });

    } catch (e) {
        console.log(e);
        throw Error(`Failed to evaluate transaction: ${e}`)
    }
}

Use Async and await function calls in both the files.

about 4 years ago · Juan Pablo Isaza Denunciar

0

Try this

 function login_user(username, password) {
        var data = {
            j_username: username,
            j_password: password
        };
    
        return axios.post("https://fakeurl.com", querystring.stringify(data))
        .then(function (response) {
            return response.status;
        })
        .catch(function (error) {
            return response.status;
        });
    }
    
    
    app.post('/auth', async function (req, res) {
        let username = req.body.username;
        let password = req.body.password;
    
        let response = await login_user(username, password);
        if (response == 204) {
            res.send("Success");
        } else {
            res.send("Failure");
        }
    });

Axios return a promise

For more info you can look at this answer here : Returning data from Axios API

about 4 years ago · Juan Pablo Isaza 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