Tips for generating and invoking a promise within NodeJS

I have been attempting to access Firestore using a function I created that includes a collection variable.

var fetchDataFromFirestore = function(collection, doc){
    return promise = new Promise(function(resolve,reject){
      //If doc param is null Query collection
      if(doc == null || doc == "" || doc == undefined){
        var response = [];
        db.collection(collection).get()
        .catch((err) => {
          console.log('Error getting documents: ', err);
          reject(err);
      })
        .then((snapshot) => {
          snapshot.forEach((doc) => {
            response.push(doc.id);
          });
          console.log(response);
          resolve(response);

        });

      }

    });
}

I invoke it with appp.get

app.get('/post', (req, res) => {
    fetchDataFromFirestore('fake',null).then(response => {
       res.json(response);
    }),(err) => {
      console.log(err);
      res.send(err);
  }

});

While it functions correctly, when attempting to test the error handling by providing an incorrect collection variable, it does not display the error message as expected.

Is there anyone who can assist me in resolving this issue?

Thank you.

Answer №1

You forgot to pass the catch handler properly.

Make this modification:

app.get('/post', (req, res) => {
    readFirestore('fake',null).then(response => {
       res.json(response);
    }),(err) => {
      console.log(err);
      res.send(err);
  }

});

to the following:

app.get('/post', (req, res) => {
    readFirestore('fake',null).then(response => {
       res.json(response);
    }, (err) => {
      console.log(err);
      res.send(err);
    });
});

Additionally, readFirestore() doesn't need to create its own promise as it is an anti-pattern. It can simply return the existing promise.

Here's a revised readFirestore() function:

function readFirestore(collection, doc) {
    //If doc param is null Query collection
    if (!doc) {
        return db.collection(collection).get().then((snapshot) => {
            const response = [];
            snapshot.forEach((doc) => {
                response.push(doc.id);
            });
            return response;
        }).catch((err) => {
            // log the error, then rethrow
            // or, if you don't need to log the error here, then just get rid of the .catch()
            // here entirely as it doesn't change your logic flow, it's only here for logging
            console.log('Error getting documents: ', err);
            throw err;
        });
    } else {
        // it's unclear what you want returned here, but you need to return a promise
        // that resolves to something - you need to fill in this logic
        return Promise.resolve(null);
    }
}

Answer №2

If you invoke your function with a Collection that does not actually exist, it will not generate an error but instead return an empty array of QueryDocumentSnapshots. This is the behavior of the JavaScript SDK.

An error will be thrown if you attempt to retrieve a Collection that is protected by a Security Rule.

As noted by jfriend00, there is no need to create your own promise since the get() method already returns a Promise. You can modify your function like this:

var readFirestore = function(collection) {
    var result = [];
    return db
      .collection(collection)
      .get()
      .then((snapshot) => {
        snapshot.forEach((doc) => {
          result.push(doc.id);
        });
        return result;
      })
  }

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

Modifying an image's height and width attributes with jQuery and CSS on click action

I'm currently developing a basic gallery using HTML, CSS, and jQuery. The objective is to have a larger version of an image display in a frame with an overlay when the user clicks on it. While this works flawlessly for horizontally-oriented images, ve ...

When querying data in Express.js and Node.js with Mongoose, the results may not match the expected outcome

One issue that occasionally arises is displaying the wrong user on the screen (someone accessing another person's session). This occurrence seems to be rare and possibly only happens during concurrent actions. If you notice anything in this code that ...

The cookie sent by the server does not replace the current cookie in place

I am currently working on an express application and utilizing the cookie-session module for managing sessions. My application consists of two paths: https://example.com/abc/def and https://example.com/abc/ghi. I have observed that when I visit one path, ...

Ensure continual control of the console during execution of a Node.js application

Is there a way to send commands to a Node.js process that is running a .js script? Currently, I am having to run the node command and manually paste my code into the console which isn't very efficient. ...

Developing a custom function within an iterative loop

Can someone assist me with a coding problem? I have these 4 functions that I want to convert into a loop: function Incr1(){ document.forms[0].NavigationButton.value='Next'; document.PledgeForm.FUDF9.value='Y1'; document.fo ...

Exploring the Node Promise Chain: Utilizing Local Functions and Managing Multiple Value Passing in a Code Review

Upon reviewing the code provided, several questions have arisen: #1 I am curious about the best way to make the values returned by the bluebird.all functions accessible in subsequent functions. Is using the this-context a viable option without declaring t ...

What is the process for sharing your website content on Google Blogger?

I am currently developing a dashboard for a small business website and I would like to implement a feature that allows users to post directly to their Blogger blog from the dashboard of their own website. This eliminates the hassle of having to switch betw ...

Looking for ways to troubleshoot errors in Stripe API calls? Seeking a node.js stack trace involving event emitters?

I'm encountering issues with my node webapp while making API calls to Stripe using the stripe npm package. Occasionally, I come across errors like the one below where the stacktrace is incomplete, leaving me unable to pinpoint the source of the error ...

Endless cycle due to $digest in AngularJS

I recently encountered an issue with an infinite loop involving angularjs $q and promises. Here's the code in question: <a ng-hide="!isTechnician()" class="pull-right" href="#/admin/techniciansState"><span ...

The usage of the bootstrapTable() function creates a gap below the displayed table information

Currently, I am working on incorporating a table into my webpage that will load data from an API. After some research, I found a Bootstrap table library to assist with this task. However, I have encountered an issue with setting the table height dynamicall ...

Why does Angular-CLI remove an old module when installing a new module using npm?

After adding the ng-sidebar module to my app, I decided to install a new module called ng2-d&d: npm install ng2-dnd --save However, after installing the new module, the old ng-sidebar module was removed from the app-module and an error occurred: C ...

Show an item in a visual format of a list

Need help displaying a specific object: cars: { number': 1, 'overload': 1,'brand': {'0': {'porsche': [{'price': 10, 'id': 0}],'vw': [{'price': 20, 'id': 1}] ...

Managing pagination in Node.js applications

I'm having trouble retrieving a specific number of rows from my database. I've been examining the query code, but can't seem to identify what might be causing the issue. Here's an excerpt of the code in question: var num_rows = offset ...

Using MongoDB's MapReduce feature along with the Date and % operator

I am encountering an issue with a Python script that I am using to aggregate large collections into smaller pieces and group them by timestamp. map = Code("function(number) {" "emit({" "ts : new Date(new Date((this.ts - (this.ts % (60 * number ...

leveraging the power of Node.js Express for the next step in

Here's a simplified version of an API function that handles post requests: myFunc(req: express.Request, res: express.Response, next){ let err = 'err detected!'; //validateSometing() returns a boolean value, true if validation pass f ...

Experience the dynamic synergy of React and typescript combined, harnessing

I am currently utilizing ReactJS with TypeScript. I have been attempting to incorporate a CDN script inside one of my components. Both index.html and .tsx component // .tsx file const handleScript = () => { // There seems to be an issue as the pr ...

Is it possible for three.js to integrate information from REST APIs?

Currently, I am in the process of learning three.js and have successfully created basic 3D models using hardcoded values. My goal now is to retrieve these values from a database that I have set up in MSSQL Server. These x, y, and z parameters are stored ...

Performing multiple queries in a single statement with Postgres and Node.js

Is it feasible to run insert and delete queries in a single statement like this? INSERT INTO COMPANY (ID,NAME) VALUES (1, 'Paul');DELETE FROM COMPANY WHERE ID='12'; Below is the snippet of my node.js code used for executing the query ...

Unable to present information retrieved from REST API, despite data being provided by the server

I'm attempting to make a REST call using a token in the header to retrieve information. To include the required header token, my code is structured as follows within my restClient.js, app.js, and users.js files. //restClient.js import { jsonServerR ...

Exploring JSON data structures using autocomplete functionalities

Here's the code I'm working with: <s:hidden id="s" value="%{Users}"/> The variable Users contains an array list of User objects. This code is written in Javascript. I want to access Users as JSON for auto-complete functionality: var valu ...