-1

I am building a react native app and have run into an issue with my promises. This code was working before, but now for some reason one of my Promises is resolving "undefined" on its own without going through its execution... I have included code to represent the flow of my App component, the logic begins in componentDidMount()

I have re-coded using traditional promises and .then and am having the same issue.

async componentDidMount() {
  console.log('call 1');
  let location = await this.getPermissions();
  console.log('finish async');
  console.log(location);
}

getPermissions = async () => {
  console.log('start 1');
  // Other logic here to determine platform, resulting in the next call
  console.log('call 2');
  let location = await this.getPosition();
  console.log('respond 1');
  console.log(location);
  return location;
}

getPosition = async () => {
  console.log('start 2');
  // Promise resolves here with "undefined" before the  
  // getCurrentPosition finishes executing
  navigator.geolocation.getCurrentPosition(
    position => {
      // Logic to find closest
      console.log('respond 2');
      console.log(closest);
      return closest;
    }
  );
}

So with the log statements, the proper flow should be - call 1 - start 1 - call 2 - start 2 - respond 2 - result - respond 1 - result - finish async - result

The output I am getting however is - call 1 - start 1 - call 2 - start 2 - respond 1 - undefined - finish async - undefined - respond 2 - result ---- this result IS correct, but promises are prematurely resolving undefined

1pocketaces1
  • 137
  • 1
  • 11
  • 2
    `getPosition` isn't returning anything, hence undefined. – Phix Jul 02 '19 at 20:38
  • It is returning something. It returns a Promise which immediately resolves with the value `undefined`, because it is an async function with no `await` expressions and no return statements. – Paul Jul 02 '19 at 20:49
  • Omitting the return statement only works with inline arrow functions. – Emile Bergeron Jul 02 '19 at 20:59
  • oh I get it, my single return is in the wrong scope. interesting that this didn't have an issue till today – 1pocketaces1 Jul 02 '19 at 21:58

1 Answers1

4

You need to make getPosition return your promise.

getPosition = async () => {
  console.log('start 2');
  // Promise resolves here with "undefined" before the  
  // getCurrentPosition finishes executing
  return navigator.geolocation.getCurrentPosition(
    position => {
      // Logic to find closest
      console.log('respond 2');
      console.log(closest);
      return closest;
    }
  );
}
caden311
  • 972
  • 8
  • 22