I am facing an issue with returning the result of an async function to the route I am calling. How can I resolve this successfully?
My goal is to export a token from file token_generator.js and display it on route ('/') using Express. The function is imported from another file.
const tokenGenerator = require('./src/token_generator');
I have a basic route set up to call that function and output the result.
app.get('/', async function (request, response) {
const identity = request.query.identity || 'identity';
const room = request.query.room;
response.send(tokenGenerator(identity, room));
});
In my token_generator, I utilize async/await to fetch and generate the token. I log it before exporting and it shows in the console but doesn't reflect on the webpage.
async function tokenGenerator(identity, room) {
const token = new AccessToken(
process.env.TWILIO_ACCOUNT_SID,
process.env.TWILIO_API_KEY,
process.env.TWILIO_API_SECRET
);
let grant = new VideoGrant();
token.identity = Math.random().toString(36).replace(/[^a-z]+/g, '').substr(0, 8);
grant.room = await getRoomId(room);
token.addGrant(grant);
console.log(token.toJwt());
return await token.toJwt();
}
module.exports = tokenGenerator;
How can I make the token appear on the webpage? I had a previous version working with similar code, but I want to follow async/await practices. Is there a different way to call the function in Express? Thank you.