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

Loading a Vue.js template dynamically post fetching data from Firebase storage

Currently, I am facing an issue with retrieving links for PDFs from my Firebase storage and binding them to specific lists. The problem arises because the template is loaded before the links are fetched, resulting in the href attribute of the list remainin ...

WebPack Error: When calling __webpack_modules__[moduleId], a TypeError occurs, indicating that it is not a function during development. In production, an Invalid hook call error

Encountering a WebPack error when utilizing my custom library hosted as a package and streamed with NPM Link. Interestingly, the production version functions flawlessly. Below are my scripts: "scripts": { "dev": "rm -rf build ...

Refreshing the Dropdown Menu with Jquery

Looking for a way to create a reusable dropdown menu using css/jquery? Check out this codepen: https://codepen.io/anon/pen/NxXXPg Is there a method to reset the 'active' status when clicking on a blank space or another html element? Here's ...

Is jQuery's $.trim() function reliable or poorly implemented?

$.trim() utilizes a specific RegExp pattern to trim a string: /^(\s|\u00A0)+|(\s|\u00A0)+$/g However, this can lead to some issues, as demonstrated in the following example: var mystr = ' some test -- more text ...

Receiving a null value when attempting to access the ids of dynamically created HTML elements using JavaScript

Encountering issue with accessing ids of dynamically generated HTML elements using javascript In my current project, I am attempting to dynamically alter the ids of div elements and remove buttons that are appended to the parent div. The desired functiona ...

Guide to showcasing console output on a Web Server

Apologies if this question is not the most suitable for this platform. I recently set up Pure-FTPd service on a CentOS server. To check current connections, I use the command pure-ftpwho, which gives me the following output: +------+---------+-------+---- ...

The dropdown feature in Bootstrap 5 seems to be malfunctioning in Angular 12

I am facing issues while trying to implement the Bootstrap 5 dropdown in Angular 12. After installing all required packages and adding them to the angular.json file, I still cannot get it to work properly. Even after copying the example directly from the ...

Ensure $q.all does not produce an error when one promise is not resolved

While geocoding addresses, there are instances where some fail. My goal is to retrieve the successful results and disregard the failed ones in order to display the coordinates on a map. Currently, using $q.all triggers the errorHandler when one promise i ...

Sending checkbox selections to JavaScript

I am currently exploring Angular by working on a chat application project. My main focus right now is on passing checkbox values to my JS code. I have included snippets of the code below. The issue I'm encountering is that I can't seem to retriev ...

Verifying the presence of a value within an SQL table

I am currently working on developing a bot that requires me to save the commandname and commandreply in a database. Right now, I am using mySQL Workbench for this task. My goal is to verify if the commandname provided by the user already exists in the tab ...

Interactive pop-up messages created with CSS and JavaScript that appear and fade based on the URL query string

I have a referral form on this page that I want people to use repeatedly. After submitting the form, it reloads the page with the query string ?referralsent=true so users can refer more people through the form. However, I also want to show users a confir ...

At what point does IE7 recalculate styles? It seems to have difficulty functioning consistently when a class is applied to the body

Currently facing a peculiar issue. I'm utilizing a class on the element as a toggle switch to control various layout behaviors on my website. When the class is active, specific actions occur; when it's inactive, these actions do not take place. ...

Exploring the Power of Modules in NestJS

Having trouble with this error - anyone know why? [Nest] 556 - 2020-06-10 18:52:55 [ExceptionHandler] Nest can't resolve dependencies of the JwtService (?). Check that JWT_MODULE_OPTIONS at index [0] is available in the JwtModule context. Possib ...

Leveraging Webworkers in an Angular application for efficient data caching with service workers in the Angular-CLI

I am looking to run a function in the background using a worker, with data coming from an HTTP request. Currently, I have a mock calculation (e.data[0] * e.data[1] * xhrData.arr[3]) in place, but I plan to replace it with a function that returns the actual ...

Is there a modal confirmation feature available in Salesforce?

if ((Modal.confirm && Modal.confirm('some unique text')) || (!Modal.confirm && window.confirm('same but different text'))) navigateToUrl('another link here','ANOTHER DETAIL','submit'); I am curious about t ...

When working with a destination module, what is the best method for storing the value that is returned from an

I have a simple function that exports data passed into a function expression. In a separate node module, I am utilizing this imported function by passing in parameters. The function is being called within a router.post method as shown below: Below is the ...

The next.js code is functioning properly when run in development mode, but encounters issues when attempting

When using the useAddress() function in run dev, it is returning undefined undefined and then the address when console logged. However, in the run build/start, it only returns undefined. What steps should I take to resolve this issue? import { useAddres ...

What is the preferred approach in JavaScript: having a single large file or multiple smaller files?

Having a multitude of JavaScript files loaded on a single page can result in decreased performance. My inquiry is this: Is it preferable to have individual files or combine them into one JavaScript file? If consolidating all scripts into one file is the ...

How can I apply a jquery method to a variable when JavaScript already has a method with the same name?

Is it possible to call the .which function on a character without needing to differentiate between browser types by using the jQuery .which method, which supposedly normalizes for browser discrepancies? I know that the inherent javascript method is also ...

unable to retrieve an object's property

Currently, I am implementing a JWT token compare function to authenticate user login by comparing the user password. However, I am facing an issue where I cannot access the user password after executing the mongoose query. exports.login = async(req, res, n ...