Assistance required in grasping the extent of this particular JavaScript variable

While working in a VueJS SPA with javascript, I am attempting to streamline my code by creating a method that passes the Google Maps Places Service a place_id and specified fields for retrieval.

getPlaceDetails (place, fields) {
  this.$refs.mapRef.$mapPromise.then((map) => {
    var placesServices = new window.google.maps.places.PlacesService(map)
    placesServices.getDetails({ placeId: String(place.place_id), fields: fields }, (result, status) => {
      if (status === window.google.maps.places.PlacesServiceStatus.OK) {
        alert(JSON.stringify(result))
        return result
      }
    })
  })
}

The above method is called from within another method:

var place = this.getPlaceDetails(place, ['name', 'geometry', 'place_id'])

The method executes successfully, displaying the desired JSON in the alert, but 'place' comes back as null. I have attempted various approaches such as setting 'vm = this' before defining 'placesServices' and assigning the result to an app level variable like so:

getPlaceDetails (place, fields) {
  this.$refs.mapRef.$mapPromise.then((map) => {
    var vm = this
    var placesServices = new window.google.maps.places.PlacesService(map)
    placesServices.getDetails({ placeId: String(place.place_id), fields: fields }, (result, status) => {
      if (status === window.google.maps.places.PlacesServiceStatus.OK) {
        alert(JSON.stringify(result))
        vm.tempPlace = result
      }
    })
  }).then(function () {
    return this.tempPlace
  })
}

I am struggling to make the method properly return the 'result' object. Any suggestions on how to achieve this?

Answer №1

Understanding Promises

A promise is like making a commitment that something will be resolved or rejected in the future. It is particularly useful for executing tasks asynchronously, such as making HTTP calls, where the time taken for completion is uncertain.

Promises can be linked together (chained) so that they are executed sequentially. The .then method plays a key role in this chaining process. By using .then, you specify a function to be executed once the previous promise is fulfilled. This function will receive the output of the preceding promise.

Implementation Example

getPlaceDetails (place, fields) {
    return this.$refs.mapRef.$mapPromise.then((map) => {
        var vm = this;
        var placesServices = new window.google.maps.places.PlacesService(map);
        placesServices.getDetails({ placeId: String(place.place_id), fields: fields }, (result, status) => {
            if (status === window.google.maps.places.PlacesServiceStatus.OK) {
                alert(JSON.stringify(result));
                return result;
            }
        });
    });
}

This method creates a promise that will eventually produce the desired outcome.

To execute this method and handle its result, you need to obtain the promise and define a function to manage it using .then. This function will run once the result is available.

this.getPlaceDetails(...).then((result) => {
    // Process the obtained result
}}

Alternatively, you can utilize the await operator to pause execution until the promise completes: var place = await this.getPlaceDetails(...);

Answer №2

If you're looking to avoid using return to handle data, one alternative approach is to store the JSON in a Vue watched data variable. Here's an example:

    var myVueInstance = new Vue({
      el: '#myElement',
      data: {
        message: 'Hello from Example.com',
        tempData: {} // <- placeholder for asynchronous data
      },
      methods: {
      fetchData (data) {
        // [...your promise code goes here...]
        }).then((response) => {
           this.tempData = JSON.stringify(response)
           // return this.tempData
        })
  // [...the .then function should be an arrow function to access tempData within scope...]

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

Struggling to create a <td> with AngularJS directive

I am currently working on creating a directive for a large set of repeated HTML code that involves using tables and table data cells. Although I have experience creating directives for div elements in the past, this is my first attempt at incorporating the ...

Steps for assigning a texture to a child Mesh within an Object3D

My Object3D was imported in the following manner: var customObject; // defining a global object var loader = new THREE.ObjectLoader(); loader.load('path/to/object3d.json', function(object) { customObject = object; scene.add(customObject ...

js expressive dynamic pattern matching

Hey there! I'm in the process of coding an online store and am currently focusing on implementing the add to cart functionality. My goal is to save product IDs and their quantities in a cookie, which will look something like this: id1:qt1,id2:qt2... I ...

Display the complete image once the loading process is finished on Angular 12

When retrieving image src via API from the server, I aim for the image to only be displayed once completely loaded. In the meantime, I would like a skeleton outline to be shown during the loading process (images are segmented into sections and the skeleton ...

Implement a Selection Feature in Angular

Currently, I am working on an application where users can add new rows with the same fields. One of the requirements is to allow users to add an option to a select element. While I have successfully implemented this in jQuery, I am facing challenges integr ...

A guide on how to automatically preselect a RadioGroup option in Material-UI

When a user selects an option from the MCQ Select using RadioGroup in my code and submits it, they should be able to return later and see the option they selected highlighted, similar to how Google Forms allows users to review their selections. Below is t ...

Ways to emphasize a specific row within a table for special occasions

I have limited knowledge of CSS and JavaScript, but I am looking for a way to create a notification highlight that functions similarly to when someone comments on a Facebook post. When clicked, it should direct me to the specific comment with a temporary h ...

Trouble with Bootstrap/CSS division not aligning left or right

I'm struggling to make my divs float left for the first one and then float right for the second one, and so on. I've attempted using float and also tried Bootstrap 5 float options, but neither seems to work. I've searched online for solution ...

Changing a variable with Functions and Objects

I'm curious to know what the index variable returns in this code snippet. I believe it will be 0. function jsTest() { var index = 0; var counter = 0; var obj = {}; obj.index = index; var func = function () { for (index ...

Tips for repositioning the color picker

Here's a straightforward example where I'm looking to adjust the location of the color picker so that it aligns with the button. function changeColor() { document.getElementById('test').click(); } <div> <h1> Colo ...

include choices to .vue document

When looking at Vue documentation, you may come across code like this: var vm = new Vue({ el: '#example', data: { message: 'Hello' }, template: `<div> {{ message }} </div>`, methods: { reverseM ...

No JSON data detected in Typescript application

My Purchase class is fairly simple: export class Purchase { customer!: Customer; shippingAddress!: Address; billingAddress!: Address; order!: Order; orderItems!: OrderItem[]; } I have a checkout component that performs the following ac ...

I am attempting to separate this "for" loop in order to generate five distinct DIV elements

Hello there! I am a beginner and I am attempting to create 5 different players by using some code that I found. Here is the code I have been working with: https://codepen.io/katzkode/pen/ZbxYYG My goal is to divide the loop below into 5 separate divs for ...

Tips for resolving JSON parsing issues within AngularJS

I am facing an issue when trying to send a contactItem (string element) from my index.html to my JavaScript application using Angular.js through http.post. Every time I attempt to post the contactItem, I encounter the following error: SyntaxError: Unexpec ...

Is it possible to make a Javascript AJAX request without using server-side code?

I am currently working on a JavaScript file where I am attempting to make an AJAX call in order to retrieve JSON data. $.ajax({ type: "POST", url: "er.js", // this is the same file data: { action: 'analyzePost&ap ...

What is the best way to retrieve the value from a React Img element?

I am having an issue with receiving 'undefined' from the console.log in 'handleClickVideo'. How can I properly extract the value when clicking on a video? I attempted using a div as well, but since div does not have a value property, it ...

Preventing flexbox containers from being affected by overflow elements

I am looking to implement overflow: scroll within a flexbox layout. I am unsure of how to link an image directly from my Google Drive, so I have provided the URL instead: https://drive.google.com/open?id=17uM5twoprxmbo5xQ37kgeTaMwn7FGSu_ When using the o ...

Expo constants failing to load on web due to unresolved manifest object issue

When setting up Firebase Auth in my expo app (using Google Auth), I needed to store my firebase variables in a .env file containing API_KEYS, AuthDomain, and more. To access these environment variables, I utilized expo constants in my firebase.ts file. Ini ...

Update the image path in Vue depending on the size of the screen

I'm looking to dynamically change the image src based on screen size in my Nuxt project. The current code I have is as follows: <div v-for="(item, index) in aside" :key="index""> <img :src="item.svgIconDark.fi ...

Utilize Backbone.js to organize and structure JSON data by populating it into nested collections and models within

I am new to Backbone.js and struggling with a complex problem. I need to save a form with infinite fields, some of which also have infinite options. My concern is that I started with a JSON response instead of building the models/collections first. Here&ap ...