Ionic 3无法在回调函数中拒绝承诺

时间:2017-10-15 14:41:13

标签: angular typescript promise ionic3

我在Ionic 3中编写了一个函数来获取用户的位置并使用用户的经度和纬度获取其地址。此功能还会检查用户的位置设置是否已启用,如果没有,则会调用this.diagnostic.switchToLocationSettings()它基本上显示用户打开的位置设置。我还添加了this.diagnostic.registerLocationStateChangeHandler方法来检查用户是否实际切换了我之前显示的位置设置中的位置。如果一切正常,我将继续运行其他过程,例如获取Geolocation并转换为地址。

以下是我的完整代码:

  getMyLocation() {
    this.geoOptions = {
      enableHighAccuracy: false
    }
    const loadingMsg = this.loadingCtrl.create({
      content: "Getting your location..."
    })

    loadingMsg.present();



    this.diagnostic.isLocationEnabled().then(test => {
        this.diagnostic.registerLocationStateChangeHandler((state)=>{
        if((this.platform.is('ios')) && (state !== this.diagnostic.permissionStatus.GRANTED ||
           state !== this.diagnostic.permissionStatus.GRANTED_WHEN_IN_USE) ||
           (this.platform.is('android')) && (state === this.diagnostic.locationMode.LOCATION_OFF )){
            return Promise.reject("Please switch on your location");
          }
       })
      if (!test) {
        this.diagnostic.switchToLocationSettings()
      }

      // return this.geolocation.getCurrentPosition(this.geoOptions)
      return this.geolocation.getCurrentPosition(this.geoOptions)
      // console.log("Error! Please switch on your location");
      // return Promise.reject("Error! Please switch on your location");
    },(err:any)=>{
      loadingMsg.dismiss();
      console.log("error : " + err);

    }).then((pos: Geoposition) =>{

      return this.nativeGeocoder.reverseGeocode(pos.coords.latitude, pos.coords.longitude);

    },(err: PositionError)=>{
      loadingMsg.dismiss();
      console.log("error : " + err.message);
      return Promise.reject(err.message);

    }).then((result: NativeGeocoderReverseResult) =>{

      this.currentAddress = result.locality+", "+result.countryName;
      loadingMsg.dismiss();

    },(err:any)=>{

      console.log("error : " + err);
      loadingMsg.dismiss();
      return Promise.reject(err);

    })
  }

问题是如果用户在this.diagnostic.switchToLocationSettings()被解雇后没有开启,我无法停止承诺链接。我试图停止链接的地方是this.diagnostic.registerLocationStateChangeHandler回调函数。我是一个承诺链接方法的初学者。

1 个答案:

答案 0 :(得分:0)

你可以这样做:

即。您可以在throw new Error('abort promise chain');return null;所需的地方使用abort promise chain

 this.diagnostic.isLocationEnabled().then(test => {
        this.diagnostic.registerLocationStateChangeHandler((state)=>{
        if((this.platform.is('ios')) && (state !== this.diagnostic.permissionStatus.GRANTED ||
           state !== this.diagnostic.permissionStatus.GRANTED_WHEN_IN_USE) ||
           (this.platform.is('android')) && (state === this.diagnostic.locationMode.LOCATION_OFF )){
            throw new Error('abort promise chain');//here
            return null;
          }
       })