Transferring the mistakes to the final return statement

I am currently working on a script that checks if a username is available or already taken. When the username is found to be taken, I need to assign an error message to my errors object. However, I am struggling with passing these errors from the inner if statement to the outer return statement. Can anyone suggest a solution for this problem?

exports.reduceUserDetails = data => {
  let errors = {}
  const userRef = db.collection('users').where('username', '==', data.username)
  userRef.get().then(snapshot => {
    if (!snapshot.empty) {
      errors.username = 'Username is already taken'
    } else {
      console.log('Username is available')
    }
  })
  return {
    errors,
    valid: Object.keys(errors).length === 0 ? true : false
  }
}

This is where I'm implementing the reduceUserDetails function:

exports.profileUpdate = (req, res) => {
  let userDetails = req.body
  const { valid, errors } = reduceUserDetails(userDetails)
  if (!valid) return res.status(400).json(errors)

  let document = db
    .collection('users')
    .where('username', '==', req.user.username)
  document
    .get()
    .then(snapshot => {
      snapshot.forEach(doc => {
        const data = doc.id
        db.collection('users').doc(data).update(req.body)
      })
      res.json({ message: 'Update Successful' })
    })
    .catch(error => {
      console.error(error)
      return res.status(400).json({
        message: 'Failed to Update'
      })
    })
}

Answer №1

One potential solution could involve abstracting the call into a new function and awaiting it in the caller. Alternatively, you may need to add an await before `reduceUserDetails()` wherever it is called.

exports.reduceUserDetails = async data => {
        
        let check = await dupChk(data);
        return {
            check.errors,
            valid: check.result
        }

}


var dupChk = (data) => (
    new Promise((resolve, reject) => {
     
        let errors = {}
        const userRef = db.collection('users').where('username', '==', data.username)

        userRef.get().then(snapshot => {

            if (!snapshot.empty) {
                errors.username = 'username taken'
                resolve({result:false,errors:errors})
            } else {
                resolve({result:true, errors: errors});//console.log('im not taken')
            }

        })

    })
);

UPDATE:

Instead of the above approach, simply modify the `reduceUserDetails()` function like so:

exports.reduceUserDetails = data => {
        
    return new Promise((resolve, reject) => {
        let errors = {}
        const userRef = db.collection('users').where('username', '==', data.username)

        userRef.get().then(snapshot => {
            if (!snapshot.empty) {
                errors.username = 'username taken'
                resolve({valid:false,errors:errors})
            } else {
                resolve({valid:true, errors: errors});//console.log('im not taken')
            }
        })
        .catch(() => resolve({result:false,errors:errors}))
    })

}

Also, in `profileUpdate()`, remember to include the `await` keyword before calling reduceUserDetails()

const { valid, errors } = await reduceUserDetails(userDetails)

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

Having trouble locating the module 'monaco-editor/esm/vs/editor/editor.worker' while using create react app

I am currently facing some challenges running react-monaco-editor in my project despite following the documentation and making necessary adjustments to my files. Below is a snippet of my package.json file: { "name": "chatbot_compiler", "version": "0. ...

Remove an element from an array based on the index provided by the front end

Currently, I am attempting to eliminate a specific item from a PHP array stored in a JSON file. Here is an example of the JSON file structure: { "1.49514754373E+12": { "description": "I don't like it", "fileNames": [ " ...

"The interconnection between NetBeans, jQuery, and AJAX is

My issue is with a Netbeans 7.4 (also tried 7.3) project involving PHP and JavaScript where breakpoints do not work in jQuery ajax loaded pages that contain included JavaScript. I have no problem with PHP or top-level JavaScript, but for example: In index ...

Tips on updating an object and adding it to an array in ReactJS with Material UI

Seeking guidance on editing an array of objects and displaying the updated value in the view. I'm new to ReactJS and attempted to do it as shown below, but found that after editing, I lose everything except for the specific one I edited. Can anyone co ...

What is the best way to turn off the annoying pop-up messages that show up for input validation, specifically the one that says "Please complete

Currently using Angular 2, my form has input fields similar to this simplified version: <input class="body-text1" type="text" [(ngModel)]="model.name" name="name" required minlength="1"> <!--more inputs like this --> Although I have implement ...

Trouble with Jsonp when using the getJSON function in jQuery

$(document).ready(function() { $.getJSON("http://quanta.net16.net/wordpressnew/test.php?jsoncallback=?", function(data) { alert('swag'); }); }); This is the JSON request I'm making and my data is properly contained within ?({object} ...

Optimizing Wordpress by Efficiently Enqueueing Javascript

As a beginner with a WordPress website, I am aware that in order to execute scripts on a WordPress page, they need to be enqueued in the functions.php file. However, I'm unsure about the correct process for this. The specific JavaScript file I want t ...

Searching for repeated values across disparate object fields?

Inquiring about the method to utilize mongoose for identifying duplicate values across different fields. Providing a sample document for reference: { "followers": { { "_id": "5bf6d610d3a3f31a6c75a9f4" }, ...

In JavaScript, utilize an object that is defined outside of a function

Here is a JavaScript function I have: function status(){ this.functionA = function(){} //Other functions and fields go here } Now, there is another function as well: function create(root){ var server = library(function (port) { //Additional functi ...

Tips for positioning the overlay to match the icon list when hovering- JavaScript/Cascading Style Sheets (CSS)

My challenge involves a list of <li>'s accompanied by an icon that, when hovered over, displays an overlay containing information about the 'test'. The setup looks something like this: test1 test2 test3 and so forth.... Here' ...

Where can you find the invalid character causing a syntax error in the jQuery $.ajax call?

My jQuery code is calling a WCF method, and although the method returns a Boolean true and logs successfully, the error handler displays "AJAX call failed in CallIsDataReady" with a "Syntax Error: Invalid character." This causes the callUpdateGrid function ...

The addition of a cancel swipe feature to an HTML5 eBook is causing the text input field for note-taking to malfunction

I am currently working on the development of a process to create HTML5 based eBooks for both desktop and mobile use using Adobe InDesign and exporting them with a plugin called In5. This plugin allows for the incorporation of html, css, and javascript duri ...

Passing parameters to JavaScript onload event from PHP

Looking for help with integrating date data from PHP into a JavaScript countdown function. I have extracted the date from a database using PHP, but struggling to pass it correctly to the JavaScript function. My attempt so far: <body onload="countIt(< ...

Is there anyone available who can assist me in removing records from my Sequelize database?

I attempted to implement the code snippet below after coming across it on a popular platform, but for some reason, it doesn't seem to be functioning as expected. Posts.delete({ where: { createdAt: { isAfter: "2016-09-11" } } }) My goal is to remove ...

Challenges associated with utilizing img src in JavaScript

I am facing a simple issue. I have carInfo data retrieved from a JSON file, but I am struggling to correctly parse the img source stored in the variable $imgsrc instead of treating it as a string called "$imgsrc". This data needs to be appended to my HTML ...

Customizing the background color of rows in Node.js XLSX using the npm package

I am currently working on a project that involves reading an Excel sheet and then coloring specific rows based on backend data. While I have successfully been able to read the sheet and create a new one with updated information, I am facing issues when try ...

Is it better to have a single object with all required modules in NodeJS, or follow the "standard" paths in the code?

Being a fan of creating global namespaces in javascript, I often use this approach in my app development. For instance, if my application is named Xyz, I typically create an object called XYZ to organize properties and nested objects like so: XYZ.Resource ...

Having difficulty loading the controller into my AngularJS module

I've been attempting to organize my angularjs controllers into separate files without success. Folder Structure: --public-- --js/controller/resturant.js --js/master.js --index.php Content of master.js angular.module("rsw",[ ...

Using JavaScript and HTML to show the current month, date, and year on a webpage

I am looking to display not only the time, but also the month, date and year. My attempted solution involved creating variables for the month, day and year, and then using getElementById. Here is an example of what I tried: var d = date.getDay(); var mn ...

Execute my function when the Redux state changes in the store in ReactJS

I am facing a specific issue in my React-Redux application. I am using Redux-saga to communicate with a REST API, which does not return a promise. Within my application, I also utilize state (in addition to the store) that I wish to update after receiving ...