2

I'm trying for my application to wait for the promise to return before executing other code, which is dependant on that data. For this I am using then(), but it is not working as expected, as the next code is still being executed, before my values are being returned.

I am using Express to handle requests and Axios to make my own requests.

index.js:

app.get('/api/guild/:serverId', async (req,res) => {
    bot.getGuild(req.params.serverId).then((response) => { // It should here wait for the promise before executing res.send(...)...
        res.send(response.data);
    }).catch((error) => {
        console.log(error) // Error: Returns that response is undefined
    });
});

bot.js:

module.exports.getGuild = async function (id){
    axios.get(BASE_URL + `guilds/${id}`, {
        headers: { 
            'Authorization' : 'Bot ' + token // Send authorization header
        }
    }).then(function (response){ // Wait for response
        console.log("Returning guild data")
        return response; // Sending the response and also logging
    }).catch(function (error){
        console.log("Returning undefined.")
        return undefined; // This is not being used in my problem
    });
}

I already know that getGuild(id) is returning a working response. It also logs Returning guild data when returning the data. Yet this is being returned after index.js returning the error, that the response is undefined. Even though it should actually wait for the Promise to be fulfilled and then working with response.data.

Log:

TypeError: Cannot read property 'data' of undefined
    at bot.getGuild.then (...\website\src\server\index.js:47:27)
    at process._tickCallback (internal/process/next_tick.js:68:7)
Returning guild data
Bendie
  • 23
  • 2
  • Avoid [mixing `async` code with `.then(…)` calls](https://stackoverflow.com/a/54387912/1048572)! – Bergi Apr 13 '19 at 13:35

2 Answers2

3

then is not needed in async functions because await is syntactic sugar for then.

getGuild doesn't return a promise from Axios, so it cannot be chained.

It should be:

module.exports.getGuild = function (id){
    return axios.get(BASE_URL + `guilds/${id}`, {
    ...

The use of catch in getGuild is a bad practice because it suppresses an error and prevents it from being handled in caller function.

Estus Flask
  • 206,104
  • 70
  • 425
  • 565
  • That worked, thanks! Yes I added the catch out of panic after trying too much stuff, I guess. I will mark this as solved, when StackOverflow allows me to. – Bendie Apr 13 '19 at 13:09
  • I call a `catch` like this a "try/hide" because that is what it does :) good note – Mark Schultheiss Apr 13 '19 at 13:39
1

The getGuild function must wait for the axios promise in order to return a result:

try {

    let res = await axios.get(BASE_URL + `guilds/${id}`, {
        headers: {
            'Authorization': 'Bot ' + token // Send authorization header
        }
    })

    console.log("Returning guild data")
    return res

} catch (exp) {
    console.log("Returning undefined.")
    return undefined;
}
filipe
  • 1,957
  • 1
  • 10
  • 23