How do I save the value of a callback function in Vue data?

#I am facing an issue where the value of this.zuobiao is not being logged after I call the function that assigns a value to it. Why is this happening?

getUserProfile() {
 uni.getLocation({
  type: 'gcj02 ',
  geocode: true,
  success: (res) => {
   this.showAddress(res.longitude,res.latitude)
   console.log(this.zuobiao); // The value of this.zuobiao is empty, why?
   uni.showModal({
    content: '坐标:' + this.zuobiao
   })
  }
 });
},
 showAddress(longitude, latitude) {
   const qqmapsdk = new QQMapWX({
      key: 'PU7BZ-42SKX-SVF4G-PE7K2-ZMFD7' //Enter your own key here  
   });
   // Tencent map API call  
   qqmapsdk.reverseGeocoder({
     location: {
      latitude: latitude,
      longitude: longitude
     },
     success: (res) => {
      this.zuobiao = res.result.address // Value has been retrieved
     }
   });
}

I have tried using async await and promise.then but they did not work. How can I successfully store res.result.address in this.zuobiao?

Answer №1

showAddress is an asynchronous function, meaning that its result will not be available at the time of the console.log. Promises are the recommended approach in this situation. Here is a guide on how to utilize them effectively...

Create async functions that return promises to handle API requests in a generic way...

async getLocation(type, geocode) {
  // todo: implement error handling
  return new Promise(resolve => {
    const success = res => resolve(res); // res object with lat/long properties
    uni.getLocation({ type, geocode, success });
  });
}

async reverseGeocoder(location) {
  const qqmapsdk = new QQMapWX({
    key: 'PU7BZ-42SKX-SVF4G-PE7K2-ZMFD7' // use your own key here  
  });
  return new Promise(resolve => {
    const success = res => resolve(res.result.address);
    qqmapsdk.reverseGeocoder({ location, success });
  });
}

By using these functions, the calling function becomes straightforward...

async getUserProfile() {
  const location = await this.getLocation('gcj02', true);
  this.zuobiao = await this.reverseGeocoder(location);
  console.log(this.zuobiao); // expected initialized value of this.zuobiao
  uni.showModal({
    content: '坐标:' + this.zuobiao
  });
}

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

Creating a facade for multiple pipes in a Gulp task: A step-by-step guide

The task specified in my gulpfile.js looks like this: gulp.task('css', function() { return gulp.src('theme.scss') .pipe(...) .pipe(...) .pipe(...) .pipe(...) .pipe(...) .pipe(...) .pipe(gulp.dest('dis ...

Using jQuery to show text upon hover using a `for` loop

I'm currently working on a webpage and incorporating a feature where hovering over specific div elements triggers the display of certain text in another div. There are 5 elements that I want to make hoverable and show text upon interaction. After imp ...

Is it possible to modify CSS properties by clicking on buttons?

Hello, I really need help with this task. I want to change the style of a button (which is actually a link) by clicking on it. These buttons are housed within a dynamic child div that changes each time, but the name of the dynamic child div remains con ...

Access cookie information within a Vue application by reading it within the router or component

There is a url (*/webapp/callback) in my vue.js app that gets redirected (http 302) from another application, bringing along some cookies. I'm trying to figure out how I can read these cookies when the component mounts and then store them in vuex stat ...

Finding the nearest span value upon clicking through a specific class

Whenever a user clicks on a hyperlink, my goal is to locate the nearest span element with a specific class and retrieve the text within that class. As of now, it is only returning blank text: Here is the provided HTML code snippet: <div class="plan re ...

Configuring lazy loaded modules with Angular 2 router

I am in the process of developing a service that utilizes router configuration to generate a map of routes based on components. Everything works smoothly except when dealing with lazy loaded module routes. I'm stuck on how to retrieve routes from a l ...

Steps to show a message on screen for a duration of 3 seconds using JavaScript

setTimeout(function(){ document.getElementById("alarmmsg").innerHTML=msg; },3000); The code above is successfully displaying the message but it's not going off the screen as expected. What might be causing this issue? ...

Can a javascript variable be accessed after loading an iframe and returning to the page?

Using a jquery plugin known as colorbox, my colorbox simply opens an iframe on the screen. This detail may not be relevant, as the core issue at hand is that I have 3 variables on my parent window that are retrieved from an AJAX call using jquery: data.re ...

Integration of Angular.js functionalities within a Node.js application

After working on my node.js app for a few weeks, I decided to add some additional features like infinite-scroll. To implement this, I needed to use packages in node.js along with angular.js. So, I decided to introduce angular.js support to the app, specifi ...

The continuous loop is triggered when attempting to pass array data from the API

Hello, I have been searching for a solution to my current issue without much success. The problem revolves around retrieving dates from Firebase and populating them into UI elements in my Vue app. My end goal is to align each date with the corresponding mo ...

Troubleshooting: Angular 2 View not reflecting changes after array push

I have encountered an issue with my two child components. They are both meant to share data from a json file that I load using the http.get/subscribe method. Oddly enough, when I try to push new data into the array, it doesn't seem to update in the vi ...

Sending a unicode PHP variable to JavaScript is a breeze

I am attempting to transfer the titles and excerpts of Persian Wordpress posts to JavaScript. Below is the code in a .php script file: function change(){ document.getElementById("link").innerHTML = '<a href="$links[2]">$titles[2]< ...

The setTimeout functionality is executing faster than expected

In my selenium test, I've noticed that the setTimeout function consistently finishes about 25% faster than it should. For example, when waiting for 20 seconds, the function completes after only 15 seconds. test.describe('basic login test',f ...

Tips for utilizing the intro.js npm package with Meteor version 1.4.1.1

I'm currently integrating intro.js into my meteor application. import { Template } from 'meteor/templating'; import { ReactiveVar } from 'meteor/reactive-var'; // import introJs from 'intro.js'; var introJs = require(&a ...

Toggling classes with Vue.js within a v-for loop

Currently, I am in the process of creating a list of items using a v-for loop. The data I am using comes from an API provided by the server. items: [ { foo: 'something', number: 1 }, { foo: 'anything', ...

Why isn't my JavaScript variable visible in the HTML code?

I am currently facing an issue with my Angular app where I am trying to display a JavaScript variable in HTML. The variable successfully shows up in an older part of my application, but it fails to do so in the new section. Below is the functional code sn ...

Evaluation of Google Closure Library's performance

When researching the performance of JavaScript libraries, I come across numerous websites that compare the speed of popular libraries including: jQuery (known for being slow) Prototype (especially sluggish in IE) Dojo (considered the fastest when it come ...

Tick the checkboxes that are not disabled, and leave the disabled ones unchecked

Currently, I am employing Jquery for the purpose of checking and unchecking checkboxes. However, some of these boxes are disabled, thus there is no need for them to be checked. Is there a method by which I can instruct the script to disregard disabled che ...

How to make an Ajax "POST" request to the server using jQuery or AngularJS without sending any parameter data

"Execute a 'POST' request to the server by using the code provided below However, the parameter data is not being sent to the server. I have attempted both the jQuery Way and var request = $.ajax({ url: baseUrl, type:'post', da ...

Nuxt's dynamic route generation results in a 400 error status code

Currently integrating Nuxt with my app and aiming to establish a connection with my server to retrieve data. To create dynamic routes, I am utilizing the built-in generate method but facing some challenges. Upon executing the generate command, I encounte ...