Most effective method for handling nested arrow function responses in Typescript

How can I properly structure a nested asynchronous function in Typescript to return a promise of an object?

  1. Is it necessary for both functions to include a "catch" block to return a Promise.reject() or is one catch block sufficient?
  2. Despite my attempts, I keep encountering the error message "A function whose declared type is neither 'void' nor 'any' must return a value" due to the absence of a return statement outside of the functions. Even enclosing everything in a try-catch block does not resolve this issue.
    async getContactByGUIDQuery(GUID: string): Promise<Contact> {
        this.findContactByGUID(GUID).then(async (query) => {
            this.querySalesforce(query).then(async (response) => {
                return response.compositeResponse[0].body
            }).catch((err) => {
                return Promise.reject(err)
            })
        }).catch((err) => {
            return Promise.reject(err)
        }) 
    }

Answer №1

Seeing that the async keyword is present, I assume you are able to utilize await in your current environment, which greatly simplifies things.

I am of the opinion that this function accomplishes the same task just fine.

  async fetchContactByGUID(GUID: string): Promise<Contact> {
    const query = await this.findContactByGUID(GUID)
    const response = await this.querySalesforce(query)
    return response.compositeResponse[0].body
  }

With an async function, a promise is returned, and if await encounters a rejected promise within your function, it will also reject with that specific error.

There's no need to handle manual rejections here - just let async/await do its job as intended.

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

What is the best way to return a Firestore promise directly to a Vue reactive() proxy?

Can you help me figure out how to handle a Firestore promise that returns an array of objects in Vue 3/Typescript and convert it into a reactive proxy object using the map() method? I want to achieve this without utilizing forEach() or Vuex. setup(){ . ...

Tips for resolving these dependency issues

After updating my Angular and my Angular project version to Angular 7, I encountered an issue when trying to run it: The package "@angular/compiler-cli" has an incompatible peer dependency with "typescript" (requires ">=3.1.1 <3.2", but would instal ...

Creating a new component when a click event occurs in React

Currently diving into the world of React while working on a project that involves mapbox-gl. I'm facing an issue where I can successfully log the coordinates and description to the console upon hover, but I can't seem to get the popup to display ...

What is preventing Apollo from achieving full transformation?

I have been struggling with an issue involving Apollo mutation for the past 2 days. Whenever I call a mutation on Angular Apollo generated code and subscribe to it, the subscription never completes. I am expecting a result from the server, but nothing is ...

Issue with editing images on the Angular front-end platform

Currently, I am developing a web application where I can input user information such as name, last name, age, birth date, and a picture. After creating a user, I should be able to delete or edit their details. However, I encountered an issue when updating ...

The application is having trouble accessing the property 'isXXXXX' because it is undefined

My attempt to utilize a shared service in one of my components has been successful when used with the app's root component. However, I encountered an error when trying to implement it on another module or dashboard. https://i.sstatic.net/x3rRv.png s ...

Indicate when a ReplaySubject has reached its "completion" signal

I'm currently looking for an effective way to indicate when a ReplaySubject is empty. import {ReplaySubject} from 'rxjs/ReplaySubject'; const rs = new ReplaySubject<Object>(); // ... constructor(){ this.sub = rs.subscribe(...); } ...

Managing a digital timepiece within a multiplayer gaming environment

I'm currently developing a fast-paced game where players control a block resembling a clock. To accurately calculate the time taken by each player to make moves, I store the start time of the game and record the timestamp of every move in the databas ...

The Component received an undefined state

One of my components was originally a class component, structured like this: interface MyState { x_data: number[] y_data: number[] order_graph_1: number } class ItemsContainerOld extends React.Component<MyProps, MyState> { constructor(props: ...

Angular Material's dialog modal swiftly closes without delay

Could you please explain why the modal opens and then closes instantly when I click on the Create Project button? https://example.com/edit/angular-code I am trying to display a component within the modal using Angular Material. portafolio.component.ts ...

Angular configuration for intercepting HTTP errors with RxJS Replay Subject

I am currently facing an issue where I am trying to retrieve the value of an error and show a customized error message using an HTML element. In order to manage the state of the error, I am utilizing a Replay Subject in my Interceptor. The interceptor is c ...

Requesting Data with JavaScript using Ajax

I'm puzzled by the behavior of an AJAX request. When I call the "done" function, I expect it to be done immediately. However, I only receive the values after using a setTimeout function. Why is this happening? {"status":"1","msg":"Return Successful", ...

Error: The module parsing process failed due to the presence of an octal literal in strict mode. To resolve this issue,

I'm currently attempting to incorporate the following regular expression into Angular6: const regexp = new RegExp('^(?:(?:31(\/|-|\.)(?:0?[13578]|1[02]))\\1|(?:(?:29|30)(\/|-|\.)(?:0?[1,3-9]|1[0-2])\\2))(? ...

What could be causing NestJS/TypeORM to remove the attribute passed in during save operation?

Embarking on my Nest JS journey, I set up my first project to familiarize myself with it. Despite successfully working with the Organization entity, I encountered a roadblock when trying to create a User - organizationId IS NULL and cannot be saved. Here ...

Replace Formik with useFormik to streamline your code

I have implemented Formik/Yup for validation on a page that triggers a GraphQL mutation. The code is functioning as expected: export default function RemoveUserPage() { const [isSubmitted, setIsSubmitted] = useState(false); const [isRemoved ,setIsRemo ...

What is the process for designating the TypeScript server side entry point in a "Nuxt TypeScript" project?

In my experience with a JavaScript-based Nuxt project, the server entry is located in server/index.js. Here is the default code for Express.js: const express = require('express') const consola = require('consola') const { Nuxt, Builder ...

Error 404 when implementing routing in Angular 2 with Auth0

In my Angular 2 application, I am utilizing Auth0 authentication. While everything works fine on localhost, I encounter issues when running the application on the server (my domain). Based on what I know, my problem seems to be with the routes. Iss ...

What is the best way to mock a Typescript interface or type definition?

In my current project, I am working with Typescript on an AngularJS 1.X application. I make use of various Javascript libraries for different functionalities. While unit testing my code, I am interested in stubbing some dependencies using the Typings (inte ...

Unraveling the mysteries of webpack configuration

import * as webpack from 'webpack'; ... transforms.webpackConfiguration = (config: webpack.Configuration) => { patchWebpackConfig(config, options); While reviewing code within an Angular project, I came across the snippet above. One part ...

Dealing with the Angular 7 ExpressionChangedAfterItHasBeenCheckedError in combination with NgsScrollReveal

Utilizing ngScrollReveal triggers a re-render with every scroll event. I am invoking a function through the HTML in this manner: <component [alternate]="toggleAlternate()"> The code for toggleAlternate() is as follows: toggleAlternate() { this.a ...