0 votes
2 views
by

In the js class, I call the apex getCityCurrentUser() method, which should return me a string, but I end up with an empty value. But the apex class works fine and gets my value from the database, which I try to return to js as a string (I make a log of this operation and see that my code exactly fills the string with the value I need). What's wrong?

@AuraEnabled(cacheable=true)
public static String getCityCurrentUser() {
    if (!Schema.sObjectType.User.fields.City.isUpdateable()) {
        return null;
    } else {
        List<User> currentUser = [SELECT City FROM User WHERE Id = :UserInfo.getUserId() LIMIT 1];
        String cityUser;
        for (User u : currentUser) {
            cityUser = u.City;
        }
        System.debug('currentCity ' + cityUser);
        return cityUser;
    }
}

This is a log entry: USER_DEBUG [98]|DEBUG|currentCity Mogilev

connectedCallback() {
        let userCity = getCityCurrentUser();
        console.log('userCity: ' + getCityCurrentUser());
        performCallout({location: 'Minsk' }).then(data => {
            this.mapMarkers = [{
                location: {
                    Latitude: data['cityLat'],
                    Longitude: data['cityLon']
                },
                title: data['cityName'],
            }];
            this.result = data;
        }).catch(err => console.log(err));
    }

This is a log entry: userCity: [object Promise]

This is a log entry (JSON.stringify): userCity: {}

1 Answer

0 votes
by
 
Best answer
let userCity = getCityCurrentUser();

An imperative Apex call returns a Promise, because it has to go to the server and back. JavaScript won't wait by default, giving you just the Promise, so you have to wait until the Promise resolves.

You have two options here. You can either use Promise.then, or await.

// If you use await, the function must be async.
async connectedCallback() {
  try {
    // Waits here
    let userCity = await getCityCurrentUser();
    // rest of code here
  } catch(e) { 
    // Handles any "reject()" from the Promise
  }

Or...

connectedCallback() {
  getCityCurrentUser()
  .then((userCity) => performCallout({location: 'Minsk' }))
  .then(data => {
      // rest of code //
  })
  .catch(e => this.dealWithTheError(e));

Or...

connectedCallback() {
  getCityCurrentUser()
  .then((userCity) => {
    performCallout({location: 'Minsk' })
    .then(data => {
      // rest of code //
    })
  })
  .catch(e => this.dealWithTheError(e));

Any way you slice it, you need to wait for the asynchronous response in order to continue.

Welcome to Memory Exceeded, where you can ask questions and receive answers from other members of the community.
You can donate any amount for Orphans village using following QR Code.
...