对异步/等待流进行故障排除

时间:2019-07-02 20:35:44

标签: javascript reactjs react-native asynchronous async-await

我正在构建一个本机应用程序,但是我的诺言遇到了问题。这段代码以前工作过,但是由于某种原因,我的承诺之一是自行解决“未定义”而不执行它的执行... 我已经包含了代表我的App组件流程的代码,其逻辑始于componentDidMount()

我已经使用传统的Promise和.then重新编码,并且遇到了相同的问题。

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;
    }
  );
}

因此,使用log语句时,正确的流程应为 -致电1 -开始1 -致电2 -开始2 -回应2 -结果 -回应1 -结果 -完成异步 -结果

但是我得到的输出是 -致电1 -开始1 -致电2 -开始2 -回应1 -未定义 -完成异步 -未定义 -回应2 -结果----这个结果是正确的,但是承诺过早地解决了未定义的问题

1 个答案:

答案 0 :(得分:3)

您需要使getPosition返回您的诺言。

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;
    }
  );
}