How can I ensure that my async function in TypeScript is functioning properly?

I am currently working on developing a Discord bot and I need to implement a feature that checks if a user is already in the database in order to create a profile for new users. Since I am still fairly new to using async functions, I have been searching for examples but have not been able to achieve the desired functionality yet.

The technologies I am utilizing include Typescript, DiscordJS, and mongoDB.

let userProfileData;
try {
  const createProfile = async () => {
    userProfileData = await profileModels.findOne({ userID: message.author.id });
    if (!userProfileData) {
      setTimeout(async () => {
        await new profileSchema({
          userID: message.author.id,
          serverID: message.guild?.id,
          balance: 0,
          inventory: [],
          bank: 0,
        }).save();
      }, 1000);
    }
  };
} catch (error) {
  console.log(error);
}

Answer №1

async function createProfile() {
  try {
    const userProfile = await userData.findOne({
      userID: user.id,
    });

    await new profileSchema({
      userID: user.id,
      serverID: message.guild?.id,
      balance: 0,
      inventory: [],
      bankAccount: 0,
    }).save();
  } catch (err) {
    console.log(err);
  }
}

Answer №2

let userData; // Kept this variable in the global scope for potential external access
async function createProfile() {
  try {
    userData = await userModel.findOne({ userID: message.senderId });
    if (!userData) {
      setTimeout(() => {
        await new userSchema({
          userID: message.senderId,
          serverID: message.guild?.id,
          balance: 0,
          inventory: [],
          bank: 0,
        }).save();
      }, 1000);
    }
  } catch (error) {
    console.log(error); // Consider using console.error for better error handling
  }
}

Remember to await the function call for accurate timing.


Given that this script is part of a discord bot and seems tied to the message_create event listener, it may be beneficial to pass message as a parameter and move this functionality outside of the event listener for improved organization.

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

Adding PHP array to a JavaScript array

I am working with an array that contains the following data: Array ( [0] => Array ( [id] => 9826 [tag] => "php" ) [1] => Array ( [id] => 9680 [tag] => "perl" ) ) My goal is t ...

What is the best way to connect users for chatting?

I am currently developing a cutting-edge chat application with a real-time communication server that allows me to send and receive messages seamlessly. The next step in my project involves mapping users for private real-time communication. I'm faced w ...

The jqGrid method is not supported on a Windows Server 2012, causing an error with the object's property

While the jq grid is working smoothly on the asp.net dev server, it encountered an error on IIS 8 (Windows Server 2012) with the message: Object doesn't support property or method 'jqGrid' JavaScript <script type="text/javascript"> ...

Increase the div id using jQuery

I've got this code snippet here and, oh boy, am I a newbie. How can I increase the number in the div using a jQuery script? if($res >= 1){ $i=1; while($row = mysqli_fetch_array($qry)){ echo "<div clas ...

Creating sleek flat buttons using WebixWould you like to learn how to

From what I've observed, the default buttons in webix appear a certain way. In a demo, I noticed "flat" type buttons that look different: Is there a way to customize my navigation buttons to look like that? I couldn't find any information about ...

What is the best way to specify an optional parameter in UI-Router without using a trailing slash?

As I was migrating my Angularjs code from ng-router to UI-Router, I encountered a challenge. In ng-router, implementing optional parameters like ":userid" was quite simple. However, I realized that the same approach is not supported in ui-router. Below are ...

Unable to smoothly animate object within OBJLoader

I'm a beginner in the world of Three JS and Tween JS, having recently picked it up for my project. However, I've encountered some frustration along the way. My main issue at the moment is trying to tween object1, amidst other objects like object2 ...

Guide to uploading a PDF to Google Drive and embedding it on an HTML static website

I manage a static HTML site for a small food shop. They require monthly menu uploads in PDF format. I believe uploading to Google Drive would be a more efficient solution than creating a separate admin view for file uploads. Can anyone advise me on how to ...

Expanding Logo on Mobile with Javascript

I'm encountering some difficulties with the site. When viewing it on a mobile device or resizing the browser to phone size, if you scroll down and then back up, the logo appears oversized. I want it to remain small like it was at the beginning (refres ...

How to pass a PHP variable to JavaScript and ensure that the echo statement reflects any changes in the PHP variable

I am currently developing a script that dynamically generates a web page using data from my database. To achieve this, I have implemented a JavaScript function that is called when the page loads and whenever there is an update required. Initially, I succe ...

Error in Typescript compiler occurs when comparing mutable enum member variables

Encountering the following error message: TS2365: Operator '===' cannot be applied to types 'ExampleState.Unsaved' and 'ExampleState.Saving'. While trying to compare an enum with a mutable member variable: enum ExampleState ...

Please include the document with a name that contains spaces

I am facing an issue where I cannot attach files with spaces in the name. However, when a file with no space in the name is successfully attached. I am using CodeIgniter for this purpose, uploading the file to the server before attaching it. I use the help ...

Sharing information between External JavaScript and React JS/Redux

Incorporating React-redux into an externalJs application (built on a custom JS framework) has posed a challenge for me. I am trying to initialize data for the Redux store from externalJS, but it seems that the external script is unable to access the React ...

JavaScript's forEach() method does not iterate through every single item

I am a beginner in javascript and I'm trying to figure out how to remove all objects with the completed property set to true. However, my current function is not achieving this. Can anyone help identify what I may be missing? const tasks = [{ ti ...

Avoid starting the stopwatch and timer at the same time

How can I control the timing of a user with a button? Currently, I can start multiple timers for different users at the same time. Is there a way to only start one timer at a time? I want the ability to pause the previous timer when starting a new one. I ...

Set the property state to false based on the value of another property in Mongoose Express NodeJS

I am trying to update the status property of a sale based on the outstandingBalance value being equal to 0. Currently, I am able to successfully update the "outstandingBalance", but I want to automatically change the status if it reaches 0. Below is the c ...

Encountering a window error while utilizing emoji-mart in a Next.js application

Thinking of incorporating the emoji-mart package into my upcoming Next.js application. I'm encountering an error while running it on localhost: ReferenceError: window is not defined file:///C:/Users/../node_modules/emoji-mart/dist/main.js (1667:47) ...

"I am having trouble with req.body in my Express JavaScript application as it is not returning the data from POST requests. Can

Being new to building an express server in NodeJS, I've been able to work on POSTs and GETs using routes and controllers. However, I'm puzzled as to why req.body is showing {} in the terminal. It seems like no data is being received from AJAX. Ca ...

Changing Highcharts Donut Chart Title Text via Legend Item Click in React

Utilizing React. In my Highcharts donut chart, there are 5 legend items of type 'number' and a 'title text' (also type: number) displayed at the center. The title text represents the sum of all the legend items. However, when I click o ...

The SMTP request for a one.com domain email is experiencing issues when sent from the render.com server

I have set up an Express JS server on render.com to handle SMTP calls to an email service hosted on one.com with a custom domain. Utilizing nodemailer to manage the SMTP call: app.post("/send-mail", validate(schema), (req, res) => { console. ...