What could be causing my promise chain to fail to resolve?

Recently, I started using promises and came across an issue with a method in my VUE component. Upon debugging, it was evident that the API was returning data and reaching the commented line.

However, upon the function's return, it failed to reach the original caller's .then method. Surprisingly, neither of the alerts I set up seemed to be working either.

I'm questioning whether I am structuring my promise chain incorrectly?

Entrance function

mounted() {
        PersonApi.Get(this.personId).then((response) => {
            alert('done');
            this.person = response;
            this.loading = false;
        }).catch((error) => {
            alert(error);
        });
    }

Library responsible for making the call

import axios from 'axios'

export default class PersonApi {
    private static ResolveApiResponse(response: any): Promise<any> {
        return new Promise((resolve) => {
            if (response.errors != undefined && response.errors.length > 0) {
                Promise.reject(response.errors);
            }

            Promise.resolve(response.Data); // code is getting to this line
        });
    }

    public static Get(id: number): Promise<any> {
        return axios.get('/api/Person/' + id)
            .then((response: any) => {
                PersonApi.ResolveApiResponse(response.data);
            }).catch((error: any) => {
                Promise.reject(error);
            });
    }
}

Updated fixed code snippet

Adjusting to the following

private static ResolveApiResponse(response: any): Promise<any> {
        return new Promise((resolve, reject) => {
            if (response.errors != undefined && response.errors.length > 0) {
                resolve(response.errors);
            }

            resolve(response.Data);
        });
    }

Answer №1

It is important to remember that when resolving a promise, you should always call the passed resolv function object instead of creating a new promise using Promise.resolve.

new Promise((resolv, reject) => {
    resolve('hello world'); // Resolving the promise
    Promise.resolve('Hello World'); // Creating a new promise that is immediately resolved
})

Typically, Promise.resolve is best used within an API when you need to return precached data or mock a calculation result.

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

The useNavigate function cannot be utilized in a custom hook created with createBrowserRouter

Presently, I've developed a custom hook specifically for handling login and logout functionalities export function useUser() { const { token, setToken, user, setUser } = useContext(AuthContext) const navigate = useNavigate() const { ...

Error: Uncaught Angular8 template parsing issue

I used a tutorial from this website to guide me through my project. However, upon running my angular application, I encountered the following error in the console: Uncaught Error: Template parse errors: Can't bind to 'ngModel' since it isn ...

Conceal the name of a property when displaying it

I have a function that retrieves data from an interface, which includes a property called name. Currently, the output includes the property name, but I would like to remove it if possible. How can I achieve this? Here is the interface structure: export i ...

The data fetched from the API is not appearing in the FlatList component on the screen, even though it is successfully logged in the console. What could be causing this issue?

After successfully fetching data from an API in my React Native app and logging it to the console, I encountered an issue where the data is not showing up in the FlatList component. const HealthLinkMain = () => { const [data, setData] = useState([ ...

Error in React Typescript hook: The function is not executable

Since transitioning the code from React JavaScript to React TypeScript, I have been encountering an issue. I had a simple hook that toggles state between on/off or true/false. I am struggling with this transition as the code used to work perfectly in Java ...

Unable to extract data from object list in Vue.js

Hi, I'm new to coding and trying to implement a function that shows related articles using Java with REST api. However, when I call the API using axios, the data is not being displayed on the view. I have checked the API and confirmed that it is retu ...

The error message "data.map is not a function" is thrown in the getStatic

I am currently working on a blog project using Strapi in conjunction with Next.js My goal is to create dynamic pages by utilizing [id].js within the pages/posts/[id].js structure However, I've encountered an issue while attempting to map through the ...

Customizing MUI DataGrid: Implementing unique event listeners like `rowDragStart` or `rowDragOver`

Looking to enhance MUI DataGrid's functionality by adding custom event listeners like rowDragStart or rowDragOver? Unfortunately, DataGrid doesn't have predefined props for these specific events. To learn more, check out the official documentati ...

Unable to change the main data of slot object in VueJS

When running this demo and selecting "modify in child", the text will be updated. However, if you choose "modify top level through slot", the text remains unchanged, and attempting to click the other button afterwards will not work. Is there a way to upda ...

Guide to organizing a calculated attribute in vue.js

I'm struggling with organizing the already computed array of results. Within Vue, I have successfully filtered images based on their ratio. Now, my goal is to sort these filtered results by date, name, or any other possible category. Although I atte ...

Error Message: The specified HTML element already contains two instances of the WebViewer, leading to a conflict in PDFTron React TypeScript Next

Having some trouble using pdftron with my docx editor. I can use the editor fine, but keep encountering an error like the one shown below: https://i.stack.imgur.com/OnJxE.png https://i.stack.imgur.com/l9Oxt.png Here is a snippet of my code: wordeditor.t ...

Encountering issues with updating subdocuments using mongoose

When attempting to update data from a subdocument using mongoose, I am encountering some issues Below is the data model: { status: 'regular', devices: [ { ip: 'deviceIp', active: true, _id: 5f4c05cb4708cf0e37a68ac0, ...

Ideas for Building a Robust Web Application: Frameworks and Database Options

Currently, I am working on developing a web application that I hope will be of large scale. This application will need to handle numerous users and store vast amounts of data, requiring a robust database system. I find myself in a dilemma when it comes to ...

A guide on iterating through a JSON object in Vue and Javascript to retrieve keys and values, checking if they are either distinct or null

Looking for a way to iterate through a JSON object that may or may not have properties fields, which can be null or contain various configurations. I need to display it in a code block. Below is the example JSON data: "grade": [ { ...

Error received from Http Get request

I am currently facing an issue with my Angular component that is supposed to make a simple HTTP Get request: this.http.get<any>('http://localhost:80/userservice/login', { params: { username: this.model.username, password: this.model.passwo ...

Can you please provide me with the compilerOptions properties needed to create a .js file from a .tsx file in React Native using TypeScript?

For the past day, I've been diving into typescript in react native. Setting up typescript in my react-native project has been a focus as I try to convert .tsx files into .js files within the realm of react native typescript. I attempted to tweak the ...

Applying background-image in ngStyle results in an undefined value

I have been attempting to incorporate images (retrieved through an API) as the background-image of an element. However, I keep encountering the error message Cannot read property 'url' of undefined, even though the URL is actually being rendered. ...

What are the steps to modify data within the root component?

I am currently working on a Vue project with vue-cli and routes. In my App.vue file, the template structure is as follows: <template> <div id="app"> {{Main}} <router-view></router-view> </div> </template&g ...

Invoking a function on an immutable object

I have a code snippet that looks like this: private get headers(): Headers { const headers = new Headers(); headers.set('Authorization', `Bearer ${this.auth.tokenSnapshot}`); return headers; } The variable headers is defined as ...

Struggling to implement React.RefObject in TypeScript

I am currently in the process of converting this class module to Typescript, but I am having trouble defining the object reference correctly. To view the example, click here. My current definition for the reference holder is as follows: private wrapperRe ...