Do not delay, MongoJS function is ready to go!

I have a function set up in my Express JS endpoint that uses 'await' to retrieve data from a Mongo DB using Mongo JS.

Function:-

async function getIntroducer(company){

  const intro = await dbIntro.collection('introducers').findOne({company: company},  function(err, doc) {
 
 console.log("🚀 ~ file: app.js ~ line 289 ~ intro ~ doc.introducer", doc.introducer)
   return doc.introducer
  });
  
  return intro;

};

Express JS Endpoint:-

app.post(
  "/case",
  passport.authenticate("accessToken", { session: false }),
  async function (req, res) {
    const body = req?.body;
    
    const intro = await getIntroducer(req.user.company);
    console.log("🚀 ~ file: app.js ~ line 1152 ~ intro", intro)

Current behavior:-


🚀 ~ file: app.js ~ line 1152 ~ intro undefined

After the result is sent, I see this in the console (indicating it's not awaiting properly):-


🚀 ~ file: app.js ~ line 289 ~ intro ~ doc.introducer 347501

I've also attempted removing 'const intro' and just directly returning it. I have also tried removing the callback function but MongoJS gives an error 'CB is not a function.'

Any assistance would be appreciated?

Answer â„–1

You are blending different approaches to asynchronous programming (callbacks and promises) when interacting with the collection.

Since the mongojs library only supports callback style, you must convert the findOne operation into a promise in order to use await.

The promisify function from the standard library module util can be of help here, as it transforms a function that takes a callback into one that returns a promise. This is achieved by ensuring the callback signature includes an error and/or a result parameter.

To promisify the findOne operation for await usage, you could implement it like this:

const util = require('util');

async function getIntroducer(company){
  const findIntroAsync = util.promisify(dbIntro.collection('introducers').findOne);
  let intro;
  try {
    intro = await findIntroAsync({company: company});
  }
  catch (err) 
  {
    // handle errors using your preferred logging method.
  }
//...
}

This approach yields a similar outcome as manual implementation. For further understanding, the Promise object is extensively discussed on MDN:

async function getIntroducer(company){
  let intro;
  try {
    intro = await new Promise(
      (resolve, reject) => {
        dbIntro.collection('introducers').findOne({company: company},
          function (err, doc) {
          if(err) {
            reject(err);
          }
          resolve(doc);
       });
    });
  } catch (err) 
  {
    // log error with your logging library.
  }
    //...
}

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

When you use the useState object in NextJS, the context object may appear to be empty

I've encountered an issue while trying to pass a context object in NextJS that uses data from a useState hook. Strangely, the state variable and setState functions are undefined when consumed. It's puzzling because substituting a simple variable ...

Array not transmitted via jQuery ajax

I am attempting to use the jQuery ajax function to send an array, but for some reason it is not functioning as expected. Below is the code I have been working with: if (section_name == "first_details_div") { var fields_arr = ["f_name", "l_name", "i ...

Unable to assign an argument to a function in commander.js

Having some trouble passing an option to a custom command in commander.js... program .command('init [options]') .description('scaffold the project') .option('-b, --build', 'add "build" folder with subfolders') . ...

Turn on / off Button Using a Different Button

I am currently working on an application that is designed to create teams using button selectors. There are two initial teams in play: the (available team) which consists of two buttons - one for selecting a player and populating the player name into the ( ...

Set the height of the div to match the length of the downward swipe

I am working on gradually revealing a div as the user swipes down on the body element. Currently, I am using jQuery along with hammer.js to detect the swipe gesture, but I need assistance in determining the distance of the swipe and adjusting the height o ...

Utilize separate environment variables for distinct environments within a React project

Is there a secure method to externalize all environment variables, including secret keys, for a React application within a DevOps setup? Our goal is to streamline the build process across different environments, each with its own unique set of environment ...

Is it possible to access the chrome://webrtc-internals/ variables through an API in JavaScript?

I couldn't find any information about how to access the logged variables in chrome://webrtc-internals/ on google. There is not even a description of the graphs available there. I am specifically interested in packetsLost, googCurrentDelayMs, and goo ...

How to send two different types of data using jQuery/AJAX to a .php file? (Syntax)

I am completely new to the world of jQuery/AJAX and I could really use some guidance. Here is the code snippet in question: $(function () { $('.button').on('click', function (event) { event.preventDefault(); //prevents ...

What is the best way to rotate an image using AngularJS?

Hey there, I've got an image that I need help rotating. There are two buttons - left and right - that should rotate the image 45 degrees in opposite directions. I attempted to create a directive using the jquery rotate library, but it's not worki ...

What is the process for comparing two objects in TypeScript?

There is a unique class named tax. export class tax { private _id: string; private _name: string; private _percentage: number; constructor(id: string = "", taxName: string = "", percentage: number = 0) { thi ...

The functionality of AngularJS's state URL depends on numerical URLs for navigation

Currently, I am utilizing the following URL in my state setup: .state('forum.spesific', { url: '/:articleId', templateUrl: 'modules/forum/client/views/forum.client.view.html', controller: 'forumCont ...

Ways to store Token in Browser Cache?

I am currently developing a login system for an application at my school. I have successfully implemented user registration, which is saved to my Azure DocumentDB. However, when trying to log in with the user, the token does not get saved so that I can acc ...

Display an array containing date objects in a dropdown menu for users to select from

I am working with an API call that returns an array of objects. Each object in the array contains a date or timestamp in ISO format. Right after my render() method, I have the following code snippet: const pickerItems = this.props.currentData.trips.map(t ...

What is the most effective method for embedding a Kotlin program into a website?

I have created a combat simulation tool in Kotlin for an online gaming community. Users can input the combat levels of two players, choose the number of duels to simulate, and then initiate the simulation which will provide win percentages and other stats. ...

What is the best way to continuously compare two date variables every minute using Javascript?

In my script, I have two date variables - one representing the current time and the other two minutes later. My goal is to compare both values every minute and trigger a function when the current time is greater than or equal to the latter time. Unfortun ...

Determine the type of sibling parameter

Creating a Graph component with configurations for the x and y axes. The goal is to utilize GraphProps in the following manner: type Stock = { timestamp: string; value: number; company: 'REDHAT' | 'APPLE' | ... ; } const props: ...

Adding Empty Space Following Error Message in Codeigniter

I am encountering an issue with my code where there is a blank space appearing after the error message. Here is the code snippet that is causing the problem: <script> const successNotification = window.createNotification({ theme: 'error&a ...

Generate a binary string using JavaScript and then transform it into C#

I have an upload section in my JavaScript program. I utilize JS FileReader to obtain a binary string of the uploaded document before sending it to my C# WebApi for storage on the server. JavaScript Code let myFile = ev.target.files[0]; if(myFile.size > ...

Persisting dynamically generated table information into a multidimensional array

I've created a dynamic table and now I'm trying to extract the data from it and store it in a multidimensional array. However, I keep encountering an exception/error that says "Cannot set property of 0 to undefined". https://i.sstatic.net/W8B9j.p ...

Error functions in Angular HTTP Interceptor are not being triggered

I followed the example code for an interceptor from the Angular HTTP documentation, but I am having trouble getting the "requestError" and "responseError" functions to trigger. The "request" and "response" functions are working as expected. myApp.config([ ...