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