Instructions on utilizing module.exports to export an async function

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.

Answer №1

const express = require('express');
const app = express();

app.get('/', async function (req, res) {
  const username = req.query.username || 'anonymous';
  const roomName = req.query.room;
  
  // Remember to use await when calling an asynchronous function
  res.send(await generateToken(username, roomName));
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

FlexSlider in WordPress is failing to display captions

Before pointing out any similar questions, please note that the answer from those sources does not apply to my specific code. I am trying to achieve this through a function as outlined here But I am struggling to figure out how to add captions only if th ...

React App anchor tag's external links fail to function properly on subsequent clicks when accessed through mobile devices

I have encountered an unusual issue with <a> anchors for external links in my React App on mobile viewports. Initially, clicking an external link opens a new tab just fine on mobile. However, subsequent link clicks on the same or other <a> elem ...

angular table disabled based on condition

I have a table in my HTML file and I am trying to figure out how to disable the onClick function if the start date is greater than the current date. <ng-container matColumnDef="d"> <th mat-header-cell ...

Achieve video lazy loading in JavaScript or jQuery without relying on any external plugins

I've been experimenting with lazy loading videos using jQuery. While I've had success with lazy loading images and background-images using the same technique, I ran into issues when trying to apply it to videos. Here's what I've tried s ...

What is the best way to make this relative path function in JavaScript?

My file structure is organized in the following way: multiple folders a subfolder _includes getStatisticsTable.php _templates StatisticsWrapper.html Within StatisticsWrapper.html, I am using jQuery's .get() method to fetch external data which ...

Is the behavior of undefined different in Chrome?

Upon examining my Asp masterpage, I noticed the following code snippet: <script> if (theForm !== undefined) { // <<== line 746: error theForm.onsubmit = ...bla bla... ; } </script> When checking the Chrome console, an er ...

Issue with ThreeJs: Difficulty loading separate images on top and bottom surfaces

I've been trying to place different textures on the top and bottom sides using Threejs to display unique images on each side. However, I'm encountering an issue where the same image is being displayed on both the top and bottom sides. Below is th ...

Choosing an option from a PHP MySQL table based on a JavaScript value

I am attempting to create a select box that displays a value based on whether the database has a "yes" or "no" in the specified column. Despite my efforts, I am unable to identify any syntax errors causing this code snippet to not function properly. JavaSc ...

Choosing between classes and styles for styling components in ReactJS

Can you explain why the call to the classes object works in the code below, rather than to the styles object defined as a const at the beginning? For instance, take a look at this demo: className={classes.button} The above line functions correctly. Howe ...

What steps should be taken when dealing with deleted documents following the execution of a #query in Mongoose?

Currently, I am in the process of removing documents from an array containing a single param referred to as slug: const selected = ['abc_1', 'aaa_2', ...] MyModel.remove({'slug': { $in: selected }}, (err, data) => { if ...

Tips for utilizing a single mongoose default connection across various files in MongoDB?

I'm struggling to figure out how to share a mongoose connection across multiple files. Here's an example: User.js var mongoose = require("../DataAccess/DbConnection"); var userSchema = new Schema({ email: {type: String, required: true,max ...

Node.js server containerized with Docker: deleted express route remains accessible

I recently developed a Twitch Chat Bot using Dockerized (docker compose), Node.js v16 with express. To create an authorize-page for users to authorize my bot on the Twitch API, I utilized the route /auth/request: this.serverUrl = serverUrl; this.port = po ...

Storing JSON data in a SQL database

Storing JSON in an MsSql database and passing it to Javascript via a PHP script has been working perfectly. However, when trying to include extra text that is not part of the formatting string, like d, h, a, or p characters, encountered some challenges. Lu ...

Checking the Signature with Elrond in the Backend using PHP

My latest decentralized application allows users to log in using their Elrond wallet and generate a unique signature containing their wallet address and additional data. As part of the authorization process, the signature is included in the payload of req ...

Having trouble with tabs in jQuery?

I'm having trouble setting up tabs in a reservation form with 3 tabs that include text boxes for user input. I can't seem to get it working properly and I'm not sure where I've gone wrong. Could it be due to the placement of the content ...

Why isn't my JavaScript variable visible in the HTML code?

I am currently facing an issue with my Angular app where I am trying to display a JavaScript variable in HTML. The variable successfully shows up in an older part of my application, but it fails to do so in the new section. Below is the functional code sn ...

Cease the execution of processes once a Promise has been rejected

My current code is functioning correctly, but I am facing an issue where if an error occurs, I want it to halt all other promises in the chain. Specifically, when chi.getCommand(val1, val2) returns a reject and triggers the exception catch block, I need to ...

Only apply prevent default on specific levels for better control

I am currently working on a menu with submenus. I am facing an issue where when I click on a top-level menu item, I need to use prevent default because they are anchor tags. However, for the submenu items, I do not want to prevent default behavior. I am st ...

A pause of 5 seconds between every request in Node.js

Need Help with Delays in Node.js Request Queue I am facing an issue with my code that involves looping through more than 500,000 records in a database and requesting information from another server. I have managed to write all the necessary functions, but ...

I'm looking to create a Vuex getter to retrieve data from the Google API documentation – can you help

Can someone help me figure out how to create a getter in Vuex store with flat data from the Google Docs API? My goal is to extract the textRun content and store it in an array because there will be multiple messages. Currently, I have hard coded this respo ...