JavaScript Promises: The response from the function is not being returned to the main code

I am currently working on a Node code that responds when a promise is resolved through the function multicreation.userCreation():

const express = require("express")
const app = express()
const csv=require('csvtojson')
const multer = require("multer")
const csvfilename = `Users-${Date.now()}.csv`
const multiUserCreation = require("./modules/fbadmin")

const multicreation = new multiUserCreation()
const upload = multer({  
     storage: storage, 
     limits: { fileSize: 1e6}
   }).single("usersdata")

app.post("/uploadCSV",function (req, res, next) { 
    upload(req,res,function(err) {   
        if(err) {   
            res.send(err) 
        } 
        else {   
            const converter=csv()
            .fromFile(`./temp/${csvfilename}`)
            .then((json)=>{
                res.send(multicreation.userCreation(json))
            })
        } 
    })
}

On the other hand, below is the code for the "multiuserCreation" class:

const admin = require("firebase-admin");
require("dotenv").config();

class multiUserCreation {
  userCreation(jsonUsers) {
    if (!admin.apps.length) {
      admin.initializeApp({
        credential: admin.credential.cert(),
        databaseURL: `https://${process.env.PROJECT_ID}.firebaseio.com/`,
      });
    }
    const db = admin.firestore();

    async function insertUsers(jsonUsers) {
      let messages = [];
      const users = jsonUsers
      for (let i = 0; i < jsonUsers.length; i++) {
        const message = await admin
          .auth()
          .createUser({
            email: jsonUsers[i]["email"],
            emailVerified: false,
            password: "password",
            disabled: false,
          })
          .then(function (userRecord) {       
            return {
              "User email": jsonUsers[i]["email"],
              Result: "Successfully created",
            };
          })
          .catch(function (error) {
            return { "User email": jsonUsers[i]["email"], Result: error.code };
          });
        messages.push(message);
      }
      return messages;
    }

    const messageFinal = insertUsers(jsonUsers);
    messageFinal.then(function (result) {
      return messageFinal;
    });
  }
}

module.exports = multiUserCreation;

Currently, even though the "messages" array is being populated successfully, multiUserCreation does not seem to be returning anything to the main code. Thank you for your assistance.

Answer №1

In order to ensure proper execution, it is crucial to return the promise from multicreation.userCreation function. Please see the modified code below:

const admin = require("firebase-admin");
require("dotenv").config();

class multiUserCreation {
  userCreation(jsonUsers) {
    if (!admin.apps.length) {
      admin.initializeApp({
        credential: admin.credential.cert(),
        databaseURL: `https://${process.env.PROJECT_ID}.firebaseio.com/`,
      });
    }
    const db = admin.firestore();

    async function insertUsers(jsonUsers) {
      let messages = [];
      const users = jsonUsers
      for (let i = 0; i < jsonUsers.length; i++) {
        const message = await admin
          .auth()
          .createUser({
            email: jsonUsers[i]["email"],
            emailVerified: false,
            password: "password",
            disabled: false,
          })
          .then(function (userRecord) {       
            return {
              "User email": jsonUsers[i]["email"],
              Result: "Succesfully created",
            };
          })
          .catch(function (error) {
            return { "User email": jsonUsers[i]["email"], Result: error.code };
          });
        messages.push(message);
      }
      return messages;
    }

    const messageFinal = insertUsers(jsonUsers);
    return messageFinal.then(function (result) {
      return messageFinal;
    });
  }
}

module.exports = multiUserCreation;

Furthermore, when invoking the userCreation method, it is advised to handle it using a callback function as shown below:

  const converter=csv()
            .fromFile(`./temp/${csvfilename}`)
            .then((json)=>{
                multicreation.userCreation(json).then(function (response) {
                   res.send(multicreation.userCreation(response))
                })
            })

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

Are JavaScript comments posing a security threat?

During a recent PCI audit, the auditor identified what they believed to be major security risks in our system: The ability to download static resources such as images, CSS, and JavaScript from our website without authentication The presence of comments i ...

Implementing validation for multiple email addresses in JavaScript: A step-by-step guide

Currently, I am utilizing Javascript to perform validation on my webpage. Specifically, I have successfully implemented email validation according to standard email format rules. However, I am now seeking assistance in enhancing the validation to allow for ...

"Rollup, Typescript, and ESLint: a trifecta of warning

I developed a project with Rollup that incorporates Typescript and ESLint along with the typescript-eslint plugin. I've noticed that ESLint is running on compiled code instead of the original source. Below is my Rollup configuration : export default ...

While trying to retrieve values from my database using react and redux, I encountered an error

Encountering an error on the server-side: Error Message: TypeError: Cannot read property 'first_name' of undefined. Additionally, the values of front-end components remain unchanged. Below is the snippet of code: const [firstName,changeName] = ...

npm was unable to locate the module named '../lib/npm.js'

Struggling with setting up nodejs and npm on a CentOS 7 machine without internet access. I tried copying the node-v6.2.1-linux-x64 folder with some lib modules to the machine, but it's throwing an error saying Error: Cannot find module '../lib/np ...

The Bootstrap tab feature is malfunctioning when a tab is using data-target instead of href

While developing bootstrap tabs for an Angular app, I decided to use the data-target attribute instead of the href attribute to avoid any interference with routes. Here's a snippet of how I structured the tabs: <ul class="nav nav-tabs" id="myTab"& ...

Implementing a Node.js Express application on CentOS server

I am currently in the process of launching a Node.js application on GoDaddy VPS hosting. After successfully uploading all the necessary files to the server, I proceeded to initialize the server using pm2 according to the instructions outlined in This Tuto ...

completing data tables and presenting them to clients

I am currently working on a website for a Nutrition specialist who requires a monthly diet regimen table with five meals daily. The doctor will be responsible for completing these tables, which will then be presented to clients. It's important that th ...

Is there a way to transfer gulp.watch() to a pipe?

Currently, I have a basic task set up for linting changed JavaScript files: gulp.task('default', function() { // monitor JS file changes gulp.watch(base + 'javascripts/**/*.js', function() { gulp.run(&ap ...

What is the concept of nested includes in sequelize?

Is it possible to perform a nested include in Sequelize? I have a table called products that has a one-to-many relationship with comments, and the comments table has a many-to-one relationship with the users table. Each comment has a user_id and product_id ...

What is the best way to find all documents based on a particular field in MongoDB?

Within my MongoDB database, I have a collection of bets structured like this: { id: String, user_id: String, type: String, events: [{ eventID: String, sport: String, evento: String, ...

What is the best way to toggle the active class on a ul list?

After clicking, the active class remains on the original "li" instead of changing as it should. I've tried modifying the code but haven't been able to find a solution. Can someone please review what I might have missed? It seems like there's ...

Distinguishing the Mouse Wheel Event

Take a look at this code snippet: <script type="text/javascript"> var scrollFunc = function(e) { var direct = 0; e = e || window.event; if(e.wheelDelta) {//IE/Opera/Chrome userMouse(e.wheelDelta); } else if(e.detail) {//Fire ...

Error message in Angular 9: "The 'pipe' property is not recognized on the 'void' type"

I recently created a function for streaming audio in Angular: private streamObservable(url) { new Observable(observer => { // Play audio this.audioObj.src = url; this.audioObj.load(); this.audioObj.play(); const handl ...

The <a href="#divtagid"> link is incapable of triggering the opening of the div tag when called from JavaScript

I need help with displaying the content of a div with the id "hello" in maindiv when clicking on the href "Click Here", but it's not working as expected. Here is the code I have: $(document).ready(function() { var newhtml = '<a href="#he ...

Steps for creating a personalized popup window

Is there a way to create a custom dialog box that includes images, input fields, and more, similar to the design on this website? Any suggestions on what tools or methods I could use to achieve this? ...

What is the best method to retrieve templates from cache or load them via ajax?

In my current code, I am attempting to retrieve templates from the cache. If a template is not found in the cache, I want to load it from the server using AJAX. Once the loading process is complete, I aim to store the template in the cache and return it. H ...

Sorting table by priority in HTML is not functioning as expected

I am currently developing this code for a SharePoint 2010 platform. While the table can currently be sorted alphabetically, I am looking to implement a different functionality. Unfortunately, I am facing an issue with changing variables 'a' and ...

Utilizing Jquery, PHP, and Mysql to Modify Values

Looking for assistance with updating an edited value in a MySQL database using jQuery/PHP. I have three buttons: edit/save/cancel When I click on the edit button, the span data is pushed into an input text field and the edit button is replaced with the s ...

EJS is failing to render

I am currently working on a rock, paper, scissors game using Node.js on the backend with an express server, frontend.js on the client-side, and index.ejs and main.css files. My goal is to display the result of the player's decision (win, lose, or draw ...