Home > front end >  How to wait for API response in separate function before continuing execution?
How to wait for API response in separate function before continuing execution?

Time:10-01

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?

CodePudding user response:

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.

CodePudding user response:

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

  • Related