Executing a function from within a promise in JavaScript

Understanding the Code

In this code snippet, there is a function named placeDecode that takes an HTML input element as a parameter. Inside this function, there is a promise used to convert the input value into a formatted address.

The function placeDecode is called twice and wrapped inside a Promise.all to ensure both calls are resolved before proceeding. However, the issue arises when attempting to call another function called viewResult, resulting in an error:

Cannot read property 'viewresult' of undefined
.


Code Overview

  //calling the function twice
    var startAddress = this.placeDecode1(this.searches.startSearch);
    var endAddress = this.placeDecode1(this.searches.endSearch);
  
    //using Promise.all
    Promise.all([endAddress,startAddress]).then(function(values) {
      this.viewResult(values);

    }).catch(function(result){
      console.log(result);
    })

    console.log('hit');
  }


  //method that converts input into a formatted address
  private placeDecode1(input: HTMLInputElement) {

    var result = new Promise(function(resolve, reject) {
      var location = input.value;

      var geoCode = new google.maps.Geocoder();
      geoCode.geocode({
        address: location
      }, function(result,status){
        if(status == 'OK'){
          console.log(result[0].formatted_address);
          resolve(result[0].formatted_address);
        }
      })
    });

    return result;
  }


Encountered Problem

The main problem faced here is with the line this.viewResult(values);, which results in the following error message:

Cannot read property 'viewResult' of undefined
Error.

Your cooperation in resolving this matter would be greatly appreciated.

Answer №1

Update:

function(data) {
  this.displayData(data);
}

To:

(data) => {
  this.displayData(data);
}

Additional Information

Arrow functions associate this depending on the outer context.

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

unable to execute PHP code

I am attempting to execute a PHP file that will update a database. On Chrome, I am encountering this error: https://i.sstatic.net/3ruNL.png This is the code I have in my index.html file: <!DOCTYPE html> <html> <body> <input type ...

An unexpected issue occurred while attempting to create a new Angular app using the command ng

Currently in the process of deploying my angular application and utilizing Infragistics. Following their Documentation, I used npm install Infragistics for installation. However, when I run ng new --collection="@igniteui/angular-schematics" I e ...

Creating an Angular table using reactive forms: a step-by-step guide

After reviewing the HTML snippet provided below, it is evident that there is a table with looping through mat cell using *matCellDef="let model". Inside each cell, there are input fields which are reactive forms. Each row or cell needs to have it ...

Generating small image previews in JavaScript without distorting proportions

I am currently working on a client-side Drag and Drop file upload script as a bookmarklet. To prepare for the upload process, I am utilizing the File API to convert the images into base64 format and showcase them as thumbnails. These are examples of how m ...

An array containing an uneven number of elements

As I was exploring how to calculate the median value of an array, my initial step was determining whether the array had an odd or even number of elements. If the number of elements is odd, then the middle element will be logged in the console. If there&ap ...

Having trouble accessing parameter values in a React app using ES6 arrow functions

Hey there! I've been attempting to send values to an ES6 arrow function in my React application, but unfortunately, it's not working. Here's what I'm trying: var data = []; for (var i=1; i<=5; i++) { data.push(<li><a href ...

Troubleshooting: jQuery AJAX .done() function failing to execute

Currently, I have a piece of code that is being utilized to dynamically load HTML into a CodeIgniter view: $.ajax({ type:"POST", url: "Ajax/getHtml", data: { u : conten ...

Converting an HTML div to a string for export

In the process of developing my application, I am utilizing an angular widget to construct a dynamic dashboard. Here is the snippet of HTML code along with the associated JavaScript that enables this functionality: <div class="page" gridster="gridsterO ...

Tips for fixing the "Function.use error: Router.use() needs a middleware function, but received an Object" issue

I'm encountering an error when calling my router from the routes directory. I've made some code changes based on other posts addressing this issue, but nothing seems to be resolving it. I'm unsure of what exactly is causing the problem in th ...

The Vue.js class bound to the object remains static even after the object is updated

When I have a number of buttons, generated using the v-for directive, with each button having an initial class based on a string from an object. There is an event that changes this string when a button is clicked. However, the class does not get updated a ...

Guide to building an interface for an object containing a nested array

While working on my Angular/TypeScript project, I encountered a challenge in processing a GET request to retrieve objects from an integration account. Here is a snippet of the response data: { "value": [ { "properties": { ...

I am struggling to resolve this "parsererror" issue with my ajax request

I am currently working on implementing ajax with django. However, I am encountering an error in the response. When I send a request to the views using ajax and create a model, I encounter issues during the process of creation. It seems like there may be a ...

Xap or js Silverlight media player

Currently developing a Silverlight video player, I stumbled upon the JW Player for inspiration. I know that Silverlight apps are typically contained within .xap files, but JW Player utilizes JavaScript scripts to implement Silverlight logic. Can you plea ...

Can Bun automatically bundle my TypeScript files when I save them in VS Code?

Is it feasible for Bun to bundle my TypeScript upon saving a file in VS Code? The instruction manual suggests running bun run index.ts in the command line and including it in the package.json in this manner. However, I am unsure how to automate this proce ...

Incorporating a timestamp to a specific cell

I'm currently developing a straightforward web application that involves: Adding table rows to an HTML site. Including a function that inserts the current time into a table cell when clicked. However, I am facing a challenge in finding examples. Wh ...

Is there a way to efficiently load a data table once the page is fully loaded?

Is there a way to load data into a table after the page has finished loading? My page includes a table, a textbox, and a search button. I have been considering using ajax, but have not found a suitable solution yet. What is the best approach for this - J ...

nighttime surveillance struggled to locate the element based on its identifier

On my page, I have the following HTML DOM structure and I am using Nightwatch to write test cases. <td class="GPNWDJGHV" id="gwt-debug-MenuItem/mongo-true">Mongo Extension</td> When trying to select the element using its ID with the '#&a ...

Create a custom loading spinner for a jQuery AJAX request

How can I add a loading indicator to my Bootstrap modal that is launched from a link? Currently, there is a 3-second delay while the AJAX query fetches data from the database. Does Twitter Bootstrap have built-in functionality for this? UPDATE: Modified J ...

Display a single button on hover in Angular 2+ framework

I'm looking to have the 'Edit' button only appear when I hover over a selected row. Here's the code: https://stackblitz.com/edit/inline-edit-change-edit2-j8b2jb?file=app%2Fapp.component.html I want the 'Edit' button to show u ...

How can I remove ASCII characters from an ajax response?

Experimenting with the API found at , but encountered an issue with properly formatting the received string. The string looks like this: Communication that doesn&#8217;t take a chance doesn&#8217;t stand a chance. The original response includes a ...