The variable loses its definition within the promise

Currently, I am developing a cutting-edge Ionic 3 application that incorporates the sensational Ionic Native Google Maps plugin. As part of my project, I aim to implement a marker pool utilizing node pool.

The hiccup I am facing revolves around the new Promise inside the createPool function. Surprisingly, the 'this.map' attribute appears to be undefined within this context, despite being established by the loadMap() operation. In my quest for answers, I stumbled upon an enlightening post discussing promises, yet its relevance to my particular scenario eludes me. Any assistance in clarifying this matter would be immensely appreciated.

ngAfterViewInit() {
    this.platform.ready()
      .then(_ => {
        return this.loadMap()
      })
      .then(_ => {
        this.markerpool = this.createPool();
        this.markerpool.on('factoryCreateError', err => console.log(err));
      })
} 


createPool() {
    var factory = {
      create: function () {
        return new Promise((resolve, reject) => {
          this.map.addMarker({
            icon: 'assets/icon/sun.png',
            visible: false
          })
            .then(marker => {
              // icon anchor set to the center of the icon
              marker.setIconAnchor(42, 37);
              resolve(marker);
            })
        })
      },
      destroy: function (marker: Marker) {
        return new Promise((resolve, reject) => {
          marker.remove();
          resolve();
        })
      }
    }
    var opts = {
      max: 60, // maximum size of the pool
      min: 20 // minimum size of the pool
    }
    return GenericPool.createPool(factory, opts);
  }

loadMap() {
    this.mapElement = document.getElementById('map');
    let mapOptions: GoogleMapOptions = {
      camera: {
        target: {
          lat: 40.9221968,
          lng: 14.7907662
        },
        zoom: maxzoom,
        tilt: 30
      },
      preferences: {
        zoom: {
          minZoom: minzoom,
          maxZoom: maxzoom
        }
      }
    };

    this.map = this.googleMaps.create(this.mapElement, mapOptions);
    this.zoomLevel = this.getZoomLevel(maxzoom);
    return this.map.one(GoogleMapsEvent.MAP_READY);
  }

Answer №1

When working with a new Promise, it's important to note that the context of this may differ from the outer scope where the map is initialized. One way to handle this is by creating a member variable inside factory and assigning it to the outer this or the map itself, then using that variable within the Promise.

var factory = {
    outerContext: this, //or outerMap: this.map
    create: ...
       ...
       this.outerContext.map.addMarker(... //or directly access this.outerMap.addMarker

Answer №2

By using an arrow function in place of create: function () {, the reference to this within the method would have pointed to the object on which createPool is invoked (which includes the map property), instead of the factory itself.

Answer №3

Consider changing var to let. Using let maintains the variable scope outside of a function. Additionally, make sure to utilize ()=>{} instead of function()

let factory = {
  create: () => {
    return new Promise((resolve, reject) => {
      this.map.addMarker({
        icon: 'assets/icon/sun.png',
        visible: false
      })
      .then(marker => {
        // setting icon anchor to the center of the icon
        marker.setIconAnchor(42, 37);
        resolve(marker);
      })
    })
  },
  destroy: (marker: Marker) => {
    return new Promise((resolve, reject) => {
      marker.remove();
      resolve();
    })
  }
}
let opts = {
  max: 60, // maximum size of the pool
  min: 20 // minimum size of the pool
}

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

Substituting placeholders within a docx template remains incomplete

Utilizing this specific library, I am implementing a feature to substitute placeholders within a docx template and generate multiple documents. The technologies involved are neutralino and vue for the front-end, where I have devised a method that transmits ...

What are the reasons for an object potentially being undefined following a *ngIf evaluation in Angular 14?

There is a scenario where we have an object defined by an interface, with the option for both category and its nested name: export interface Product { category?: { name?: string, } } The objective now is to display an element only if both the cate ...

In the context of NextJs, the req.body is treated as an object within the middleware, but transforms

Here is the middleware function responsible for handling the origin and CORS: export async function middleware(request: NextRequest) { const requestHeaders = new Headers(request.headers) const origin = requestHeaders.get('origin') ?? '& ...

Utilize the withCredentials property in conjunction with $resource

I am looking to utilize a resource with a cookie set in the navigator. Using $http makes it simple, just need to set withCredentials to true: $http({ method: 'POST', url: url, data: user, withCredentials: true }); However, for ...

Manipulating prop values through dropdown selection

I'm currently working on implementing filtering based on a prop value that changes according to the dropdown selection. Here's my progress so far: template(v-for="field in tableFields") th(:id="field.name") select(@change="filterScope(sc ...

What is preventing the console from identifying the ID?

I'm working on a project that involves displaying the id, latitude, and longitude in the console. The goal is to save this information in an array and then store it in a mysql database using the Google Maps Javascript API. Below is the code: <scr ...

visit a new page with each reload

Can I navigate to a new page without refreshing the current window.location.href? I attempted to achieve this using a jQuery event handler on the window object, however, it doesn't seem to be functioning properly. $(window).on('reload', fu ...

Each time the page renders, LocalStorage is initialized with a fresh empty array

I've encountered an issue while trying to update my localStorage with new items added to my shopping cart. Each time an item is added, an empty array appears before it (see screenshot). Can anyone explain why this is happening? I'm considering u ...

Encountering a challenge in Angular 8: Unable to locate a supporting object matching '[object Object]'

I am having an issue trying to retrieve the Spotify API from the current user's playlists. While I can see it in my console, when I attempt to insert it into HTML, I encounter the following error: ERROR Error: Cannot find a differ supporting object ...

What is the best way to incorporate CSS conditions within a function?

After creating a filter function in React to organize images by category, I encountered an issue where the filtered images weren't centered as I wanted them to be. I am now looking for a way to integrate centering into the filtering process so that wh ...

Executing a script that has been inserted into the page post-loading

I'm facing an issue where the script tag at the bottom of my project is not being executed after adding new pages later on. Main const fetch = (url, call) => { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if ...

"Encountering a 400 Bad Request error while trying to implement

I run a website that utilizes AJAX requests and history.pushState for navigation. The content requested includes Google's asynchronous AdSense code: <ins class="adsbygoogle" style="display:inline-block;width:468px;height:60px" data-ad-c ...

Accessing instance variables from a chained observable function in Angular 2/Typescript

Currently, I am utilizing Angular2 along with Typescript. Let's assume that there is a dummy login component and an authentication service responsible for token authentication. In one of the map functions, I intend to set the variable authenticated as ...

Execute JavaScript code once the XMLHttpRequest has completed execution

I'm facing an issue where the JavaScript code is executing faster than the XMLHttpRequest. I am hesitant to resolve it using: setTimeout(function() {}, 100); Below is a snippet of my code: function change_country(id) { if (window.XMLHttpReques ...

To modify the specified variables in data, I must deconstruct the object

Hello everyone, this is my debut post. I am seeking assistance with destructuring in order to update a variable that is defined within the "data" section. Below are the code snippets I have been working on using Vue. data: () => ({ id: '' ...

Creating visually appealing tables in React.js

Having trouble with table rendering in React. The buttons in the table cell are not styled properly and do not center within their div. Additionally, the table border is cut off where there are buttons or empty headers. Need help figuring out what's g ...

JavaScript maintaining records and connections between multiple asynchronous events

I am working on an Angular 10 project where users can compress and upload images to Google Cloud Storage. The compression and uploading functionalities are functional, but I'm facing challenges with managing the asynchronous process of handling multip ...

Having difficulty applying capitalization to the initial word in an input using JavaScript/jQuery

I've read through several other discussions on this forum regarding the same issue. My problem lies in capitalizing the first letter of an input. Here is the link to my code on JSFiddle Despite my efforts, I can't seem to get the substr() funct ...

Can someone explain the process of unescaping characters in an API response to me?

I have created an application that leverages AngularJS to pull data from the WP Rest API V2. The response includes escaped characters, like the example below: "excerpt": { "rendered": "<p>When we go shopping, we encounter many different labeling ...

Using NodeJS to perform asynchronous tasks with setImmediate while also incorporating private class

Today marks my first time experimenting with setImmediate. I've come to realize that it may not be able to run private class methods. Can someone shed some light on this? Why is that the case? Not Functioning Properly When trying to use a private cl ...