I have an Express.js / Node.js API project where I am calling a endpoint that depends on an internal async function.
const express = require('express');
const fetch = require('node-fetch');
const router = express.Router();
module.exports = router;
async function getToken() {
fetch("www.example.com", {
method: "post",
headers: {
"Authorization": "Basic " + btoa(userName + ':' + password),
"Accept": "application/json"
}
})
.then(response => response.json())
.then(json => {
console.log(json)
return { response_code: 200, response: json }
})
.catch(err => {
return { response_code: 500 }
})
}
router.get('/getAll', async (req, res) => {
var token = await getToken()
console.log(token)
res.status(200).json({'response': token})
})
What I want here is that function getToken()
should be able to be called from multiple endpoints. For example, when /getAll
endpoint is called, it gets the token from getToken()
first and then proceeds with its own logic. For this I am using await
keyword.
But when I call the /getAll
endpoint, I get undefined
in the return value of await getToken()
. I have checked using console.log()
and I can see that the console
in /getAll
gets called first, and after that I get the actual token value that is being logged from inside async function getToken()
.
Why is this happening and what can I change to get the token value from my function?