Error: Unhandled promise rejection - The function get is not part of this.categoryMap

I am facing an issue with calling functions of the Map (get, set, keys, etc) within my function. The map I am working with is returned from a firebase query.

Here's a snippet of my code:

categoryMap = new Map<Number, String>();

//called onInit.
loadList() {
this.firestore.firestore.collection('skillType').doc('content')
  .get().then(res => {
      this.categoryMap = res.data().list;
      });
}

sampleFunction() {
    //myMap is a dummy map that I found online.
    var myMap = new Map();
    myMap.set(0, 'dummy'); //the function works here.
    console.log(myMap.get(0)); //Outputs as expected.
    console.log(this.categoryMap.get(1)); //Throws an error message instead
}

This is the categoryMap after executing loadList():

1: "Development & IT"
2: "Design & Creative"
3: "Accounting & Consulting"
4: "Translation & Language"
5: "Sales & Marketing"
6: "Sports & Fitness"
7: "Academic & Curricular"
8: "Culinary"
9: "Labor work"

The values are present in the map, so why am I unable to call any functions to retrieve my data?

Answer №1

An issue arises with this particular promise because loadList resolves immediately without waiting for it to finish. To address this, it is recommended to utilize async/await instead of promise chaining. The following example demonstrates how you can resolve this issue by integrating async/await into your existing solution based on your specific requirements.

let categoryMap = new Map<Number, String>();

const populateList = async() => {
  const snapshot = await firestore.firestore.collection('skillType').doc('content').get()
  categoryMap = snapshot.data().list
}

const sampleFunction = async() => {
  // Ideally populate the list only when needed or in the onInit method
  await populateList()
  // The map is now populated
  console.log(categoryMap.get(1)) 
}
sampleFunction()

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

Toggle the opening and closing of React components with a map function using onclick

Implementing an onClick function within a map operation, I am encountering an issue where clicking the onClick button changes the state of all items in the map, instead of just the item clicked. This is being done using the useState hook. const [open, se ...

Fixing the problem of digest overflow in AngularJS

I've been working on a code to display a random number in my view, but I keep encountering the following error message: Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting! It seems to be related to a digest outflow issue, and I&apo ...

Enhancing Firebase push notifications with multilingual support

Looking to localize the push notifications I receive on my Android/iOS device using Firebase notifications. There's an option in the console to filter language, but I can't find any documentation on how to use it effectively. I have two main ques ...

Styling CSS according to the specific words found within the content

After retrieving text data from an API, I want to enclose a specific word, for example "Biography", with <span> and </span> tags in order to apply unique styling. Can anyone provide guidance on how to accomplish this using jQuery or JavaScrip ...

How to use OBJLoader/Three.js to load a specific URL in JavaScript

I am encountering an issue with a JavaScript code snippet from the three.js OBJloader. I should mention that my experience level in JS and PHP is limited as I am just starting out with WordPress websites. My problem lies in utilizing the setPath and load ...

Angularjs: a powerful tool for passing data efficiently between controllers

In my angular.js application, I have implemented multiple views and I am in need of maintaining the status across view changes. To achieve this, I have created a simple factory to share data between controllers. Instead of using "$scope" in the controllers ...

Retrieve the number of rows in the table component

I'm in need of getting the row count from a table component that I have built using vuejs. My goal is to display the row count outside of the table component structure. The issue with the code snippet below is that it doesn't show the correct row ...

Problem with Java class in GWT JsInterop

Having some trouble with JsInterop while wrapping up a piece of JavaScript code. The JavaScript code looks like this: com = { gwidgets: {} }; com.gwidgets.Spring = function () { this.name = "hello"; }; com.gwidgets.Spring.prototype.getName = ...

Is the Angular Karma test failing to update the class properties with the method?

I am struggling to comprehend why my test is not passing. Snapshot of the Class: export class Viewer implements OnChanges { // ... selectedTimePeriod: number; timePeriods = [20, 30, 40]; constructor( /* ... */) { this.selectLa ...

A guide on successfully sending parameters to Angular routes

Currently, I am delving into Angular and exploring various basic concepts such as routing, Observables (and subscribing to them), making HTTP requests, and utilizing routing parameters. One scenario I have set up involves sending a HTTP GET request to JSON ...

JavaScript: Controlling the ability to enter text based on the chosen option from a drop-down menu

After struggling to make my code work, I decided to create a piece of JavaScript to disable a text input when "Cash" payment is selected from the dropdown menu. On the contrary, I aimed to enable the text input if "Credit Card" payment was chosen. Unfortun ...

Creating an app for sending text messages and making video calls with Spring Boot technology

I am interested in developing an application with Spring Boot that allows users to make video calls and share text messages. I also want the ability to save these videos for future viewing by registered users of the app. Although I am familiar with node.j ...

How can you use JavaScript and regex to extract the word before a comma?

Hey there, I'm attempting to extract the word right before a comma in a sentence. For instance, consider the following string: "Cloudy, and 51 ° F " I aim to retrieve CLOUDY as the output. Could someone guide me on how to achieve this using regex ...

Having trouble showing table data in Angular

My goal is to showcase data from a table created using Spring-Boot Below is my model.ts: export class Quiz1 { QuestionId?: any; Question?: string; OptionsA?: string; OptionsB?: string; OptionsC?: string; OptionsD?: string;} He ...

"An issue with the colyseus server has been detected within the JavaScript code

I have written some code but it seems to be causing errors. const colyseus = require("colyseus"); const http = require("http"); const express = require("express"); const port = process.env.port || 3000; const app = express(); ...

Is using .htaccess a reliable method for securing a specific file on the server?

Running a classifieds website comes with its own set of challenges, one being the need for an administrator to have the ability to remove classifieds at their discretion. To address this issue, I have developed a simple function that allows me to specify t ...

Fixed Navigation Menu on Top with Specific Width Size

Currently diving into the world of CSS and eagerly following a tutorial on creating a responsive menu for my website. Managed to get it up and running, but hit a few roadblocks along the way: The navigation menu seems to shrink in both desktop and mobile v ...

What is the best way to choose an item from a dropdown menu using JavaScript?

Is there a way to set the dropdown value from the client side? Currently, I am loading countries and states using a countries.js file on grid row selection for updating. However, because it is loaded from the client side, I am unable to load country and st ...

Modifying the row background in a DataTables drawCallback

Is there a way to dynamically change the background color of a row based on a specific value in a cell using drawCallback? $(table_id).DataTable({ //... "drawCallback": function (settings) { // Here, if the type of data in a particular ce ...

Is it possible to combine ng-class with conditional expression and ng-class with string syntax in a single statement?

To assign classes based on the ngRepeat index, I am using ng-init="myIndex = $index". With this setup, I can apply classes like color-0, color-1, color-2, etc. by using ng-class='"color-" + myindex'. Furthermore, I need to add a different class ...