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

Sharing slices of data among feature modules in NgRx allows for improved scalability and organization

I'm a newcomer to the world of NgRx and I find myself with some inquiries regarding the proper way to organize the state within a Store. Currently, we are in the process of developing an internal CRM system using Angular to manage client information. ...

Addressing the reactivity issue when incorporating basic markdown directive into vuejs

In an effort to reduce dependency on vue-i18n formatting, I decided to create a simple Markdown formatter directive that only implements bold, emphasize, and strike-through styles. The current implementation of the directive is as follows: import _Vue ...

Understanding the attribute types in Typescript React

While working on code using Typescript + React, I encountered an error. Whenever I try to set type/value in the attribute of <a> tag, I receive a compile error. <a value='Hello' type='button'>Search</a> This piece o ...

Tips for implementing a search filter in a select dropdown menu using Angular

I am attempting to enhance my select option list by including a search filter. With numerous options available, I believe that having a search function will make it easier for the user to locate their desired selection. I hope my message is clear despite ...

Creating click event handler functions using TypeScript

I encountered an issue when trying to set up an event listener for clicks. The error message I received was that classList does not exist on type EventTarget. class UIModal extends React.Component<Props> { handleClick = (e: Event) => { ...

Troubleshooting issue: Angular 7 navigation function not functioning within an 'if' statement

AppComponent.ts if(result['status'] === 'success'){ this.router.navigate(['/dashboard']) //return false alert("Login successful!"); } else { alert("Invalid login credentials"); } The "Login successful!" aler ...

Receive the most recent query in a Nuxt plugin following the completion of page loading

So, here's the issue - I have a plugin containing some functions that are supposed to update URL queries. However, every time I run $global.changePage(2) or $global.changeLimit(2), the console.log(query) outputs an empty object and doesn't show t ...

Changing the tag value within a directive

Imagine you have the following template: <p title>Hello Universe</p> How can I dynamically replace "Hello Universe" with a different string using a directive? I attempted the following approach, but it was not successful: @Directive({ sel ...

Executing a node.js function within an Angular 2 application

Currently, I am running an Angular2 application on http://localhost:4200/. Within this app, I am attempting to call a function located in a separate node.js application that is running on http://localhost:3000/. This is the function call from my Angular2 ...

Error: FullCalendar does not display a header for the timeGridWeek view when the dates fall

Currently, I am integrating fullcalendar 5.5.0 with Angular 10. After migrating from fullcalendar v4 to v5, I noticed an annoying issue where the header for the date before the validRange start is no longer displayed: These are the parameters being used: ...

Customizing hover color with tailwind CSS

How can I change the color of an icon on mouseover using Tailwind CSS? I have tried to go from this to this , but it's not working. .btn { @apply agt-h-10 agt-w-10 agt-bg-zinc-100 agt-rounded-full agt-flex agt-justify-center } .img{ @apply agt ...

How to handle form-data in NestJS Guards?

I've been trying to access form-data in my NestJS Guards, but I'm experiencing some difficulties. Despite following the tutorial provided here, I am unable to see the request body for my form-data input within the Guard itself. However, once I ac ...

The benefits of exporting a component from one module and using it in another module

After putting in long hours trying to figure this out on my own, I've finally decided to seek help from the community. Thank you in advance for any assistance! I have a Web Projects Module that utilizes a Webpage Component. Within the Webprojects Mod ...

The MongoDB connection in NextJS 14 is causing a delay in loading the page

Occasionally, when trying to open a page through the dashboard menu, nothing happens on the frontend. There's no loading screen or any indication that the page is being loaded. How can this problem be prevented so that the page loads as intended? This ...

Efficiently communicating updates to clients after executing multiple HTTP requests simultaneously in RxJS

Objective: Execute multiple asynchronous HTTP requests simultaneously with RxJS and trigger a callback after each request is completed. For instance: fetchData() { Observable.forkJoin( this.http.get('/somethingOne.json').map((res:Re ...

Error in Angular2 routes: Unable to access the 'forRoot' property

angular2 rc.5 I encountered a problem with TypeError: Cannot read property 'forRoot' of undefined(…) after investigating, I discovered that RouterModule is appearing as undefined during execution. This is my app.route.ts: import {Routes, Rou ...

Leveraging the ngFor local variable within nested elements

Is there a way to properly display a property of the local variable theme, such as theme.name? Below is an example of how my *ngFor is structured: <ul> <li *ngFor="#theme of themes"> <span>theme.name</span> </li> ...

An error occurs in TypeScript when attempting to reduce a loop on an array

My array consists of objects structured like this type AnyType = { name: 'A' | 'B' | 'C'; isAny:boolean; }; const myArray :AnyType[] =[ {name:'A',isAny:true}, {name:'B',isAny:false}, ] I am trying ...

Encountering a type error while trying to read dummy data, as the map function is not

I am currently working on fetching dummy data from a URL in my component using TS and Next.js. Unfortunately, I encountered an error type that I am unable to diagnose. typings.d.ts: export type Themen = { id: number; title: string; description: string; ...

Utilize Angular2 to dynamically add new routes based on an array register

Currently, I am utilizing Angular2 for the frontend of my project and I am faced with the task of registering new Routes from an array. Within my application, there is a service that retrieves data from a server. This data is then stored in a variable wit ...