Issue with rejecting a promise within a callback function in Ionic 3

Within my Ionic 3 app, I developed a function to retrieve a user's location based on their latitude and longitude coordinates. This function also verifies if the user has location settings enabled. If not, it prompts the user to switch on their location services by calling

this.diagnostic.switchToLocationSettings()
. Additionally, I implemented the
this.diagnostic.registerLocationStateChangeHandler
method to confirm whether the user has indeed enabled location services after being prompted. Once all checks are passed, the function proceeds to fetch the geolocation and translate it into an address.

Below is the complete code snippet:


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)

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

})
}

An issue I encountered was my inability to halt the promise chaining process if the user failed to enable location services after the prompt triggered by

this.diagnostic.switchToLocationSettings()
. I attempted to stop the chaining within the
this.diagnostic.registerLocationStateChangeHandler
callback function without success. As a novice in using promise chaining techniques, any guidance on how to resolve this would be appreciated.

Answer №1

If you want to stop a promise chain, try this approach:

For example, insert

throw new Error('abort promise sequence');return null;
at the specific point where you wish to stop the promise chain.

 this.someFunction().then(data => {
        this.anotherFunction((result) => {
        if(someCondition){
            throw new Error('abort promise sequence');//execution stops here
            return null;
          }
       })

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

When compiling my TypeScript file, I encountered an error stating that a block-scoped variable cannot be redeclared

In my Visual Studio Code, I have written just one line of code in my ex1.ts file: let n: number = 10; Upon compiling using the command tsc ex1.ts, the compiler successfully generates the ex1.js file. However, VSC promptly displays an error in the .ts file ...

Error occurs when using JSON.stringify with a Typescript array map

When running this code snippet in Typescript: [].map(JSON.stringify); An error is being thrown: Argument of type '{ (value: any, replacer?: ((key: string, value: any) => any) | undefined, space?: string | number | undefined): string; (value: a ...

Utilizing the component as both a custom element and an Angular component

I have been experimenting with using an Angular component as a custom element, allowing me to dynamically add it to the DOM and have it automatically bootstraped. However, I also need this component to be included in another component's template. Cur ...

Angular array sanitization for handling multiple URLs

I need to sanitize multiple URLs from an array containing links to video sites e.g.: videos: SafeResourceUrl = ['www.someURL1', 'www.someURL2',... ]; To achieve this, I created a constructor like so: constructor(private sanitizer ...

Creating unique components with Angular2 and Ionic

Here is the HTML code for my custom component: <div> {{text}} {{percentLeft}} {{innerColor}} </div> And here is the TypeScript file for my component: import { Component, Input } from '@angular/core'; @Component({ selector: ...

Scully.io prerenders the ROOT route as a static file, but it does not prerender any other routes in its process

Our production Angular 14.2.12 application is running smoothly. I decided to generate static pages using Scully, so I followed these steps: Run the command: ng add @scullyio/init This added Scully to my project. Next, I executed "ng build" and "npx sc ...

Guide to encoding an array of objects into a URI-friendly query string using TypeScript

Just getting started with typescript and looking for some help. I have an input array structured like this: filter = [ { field : "eventId", value : "123" }, { field : "baseLocation", value : "singapore" } ] The desired format for ...

Error: Disappearing textarea textContent in HTML/TS occurs when creating a new textarea or clicking a button

I've encountered an issue with my HTML page that consists of several textareas. I have a function in place to dynamically add additional textareas using document.getElementById("textAreas").innerHTML += '<textarea class="textArea"></text ...

Is array.length access cached by NodeJS?

Lately, I've been pondering whether accessing the array.length getter is cached by NodeJS. I've searched for conclusive answers about JS interpretation in browsers, but since I am working on apps in Typescript, that information does not directly ...

Distinguish between multiple occurrences of the same component in Angular 2

I've recently started learning Angular 2 and have a query regarding components. I have created a component called "dropdownComponent" that generates dropdown components. However, when using this component multiple times, I'm unsure how to differe ...

Keep the code running in JavaScript even in the presence of TypeScript errors

While working with create-react-app and typescript, I prefer for javascript execution not to be stopped if a typescript error is detected. Instead, I would like to receive a warning in the console without interrupting the UI. Is it feasible to adjust the ...

Refresh Angular Component upon query parameter modification

Within my application, there is a search form that can be accessed by adding query parameters to the URL. This will prefill the form with specific information. My goal is to clear this prefilled state when the search icon in the navigation is clicked. Whi ...

Typescript constructor that accepts an object as an argument instead of traditional parameters

My constructor is becoming lengthy and not structured the way I would prefer. I am looking to pass an object to my constructor so that I can access fields by their names. Here is how the class looks currently. export class Group { id: string; constru ...

I possess an item, but unfortunately, I am only able to save the first object from this possession

I have an object, but I can only save the first item from this object. Interface: export interface PhotoToCreate { albumName: string; albumTitle: string; ImageNameO : string; imageNameT : string; } Component import { Component, OnI ...

Leverage the generic types of an extended interface to simplify the creation of a shorthand type

Attempting to streamline my action shorthand that interacts with AsyncActionCreators. A function has been crafted to accept a React dispatch: Dispatch<T> parameter: const fetchProfileAction = actionCreator.async<void, Profile, any>('FETC ...

Setting null for HttpParams during the call

I am encountering an issue with HttpParams and HttpHeaders after upgrading my project from Angular 7 to Angular 8. The problem arises when I make a call to the API, as the parameters are not being added. Any assistance in resolving this matter would be gre ...

Error: Missing 1 type argument(s) in generic type definition

I've developed an abstract class structure as shown below: export abstract class CsvFileReader<T> { data: T[] = [] constructor(public file: string) {} abstract mapRow(row: string[]): T read() { this.data = this.file .split(& ...

Storing information from a signup form using Angular

Can you help with my registration form? <div class="form-group"> <label for="email" class="col-sm-3 control-label">Email Address</label> <div class="col-sm-9"> <input type="email" id="email" placeholder="Enter your ...

Troubleshooting a cross-component property problem involving a fetch request within a subscription

My current objective is to utilize ActivatedRoute parameters to make a fetch request and update a class property with the fetched data. Progress has been made on making the request, but I am facing difficulties in getting the fetched data to the specific c ...

Steps for customizing the default properties of a material ui component

Is there a way to change the style properties listed on the main element? height: 0.01em; display: flex; max-height: 2em; align-items: center; white-space: nowrap; } <InputAdornment position="end" > {"hello& ...