Discovering the world of Promises in TypeScript and understanding how to return specific types

Transitioning from coding in Clojure for the past two years to TypeScript has been an interesting journey. However, I've hit a bit of a roadblock today.

The issue lies with my interface:

interface ICustomer {
  id: number,
  first_name: string
 }

I need a function that can consume an API, retrieve customer data, and return it as per the defined interface. The problem arises when dealing with "async" functions like:

async consultApi( id: number ): Promise<any> {
  const customer = await SomeExternalApi.getCustomer(id);
}

This function always returns a promise, but what I actually want is the object from the "SomeExternalApi.getCustomer" method. So, I attempt to handle this by creating another async function:

async getCustomer( id: number ): Promise<any> {
  const customer = await consultApi(id: number );
}

However, as expected, this also returns a promise instead of the desired customer data. How can I break out of this cycle?

One solution might be to avoid using async functions and try something like:

return Promise.then(response => response.json)

In a synchronous function. But, I suspect the root cause of the problem is my limited experience with TypeScript. How do TypeScript developers effectively use "async" functions to obtain resolved data and return it within a fulfilled Interface, rather than just a Promise?

Answer №1

Regrettably, an async function is limited to returning only a promise. Whenever you make a call to an API and await a response, it involves asynchronous actions that cannot be immediately resolved.

return Promise.then(response => response.json)

Even utilizing the then() method on a promise (not the Promise constructor) will still result in a returned promise, as it signifies actions to be executed post-promise resolution.

Since the API request outcome has not been transmitted at the time of the request, immediate return of the result is unattainable.

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

Convert parameterized lambdas for success and failure into an observable using RxJS

There is a function exported by a library that I am currently using: export function read( urlOrRequest: any, success?: (data: any, response: any) => void, error?: (error: Object) => void, handler?: Handler, httpClient?: Object, ...

Is there a way to programmatically control a Bootstrap Dropdown in Angular?

Need help with opening and closing a Dropdown in my View using my typescript class. Any suggestions on how to achieve this? Appreciate any assistance! <div ngbDropdown class="d-inline-block"> <button class="btn" id=&quo ...

What methods are available for drawing on an HTML canvas using a mouse?

I am facing two challenges: how can I create rectangles using the mouse on an HTML canvas, and why is my timer not visible? Despite trying various code snippets, nothing seems to be working. Grateful for any help! HTML: <!DOCTYPE html> <html lan ...

Leveraging AnimatePresence from the Framer Motion library to design an exit animation for a motion.div

My goal is to implement a side menu that smoothly slides in and out when the menu/close button is clicked using framer motion. Initially, clicking on the menu button will cause the menu to slide out from the left side of the screen while changing the butto ...

Managing properties of classes within callbacks using TypeScript

I am currently working on the following task: class User { name: string; userService: UserService; //service responsible for fetching data from server successCallback(response: any) { this.name = string; } setUser() { ...

What is the best way to dynamically load content as it enters the viewport using JavaScript or jQuery?

I have implemented a stunning animation to the h1 element using a function, but now I want the animation to trigger only when the h1 element enters the viewport as the user scrolls down. Currently, the animation occurs as soon as the page is loaded, even ...

Having trouble retrieving response content in Mithril

I've been experimenting with making a request to a NodeJS API using the Mithril framework in my client application. I attempted to fetch data by following their example code: var Model = { getAll: function() { return m.request({method: "G ...

Error Message: Angular NullInjectorException - The provider for "[Object]" is not found

While developing a simple Flashcard application that performs CRUD operations using Angular, Node.js, Express, and PostgreSQL, I encountered the following error: flashcards-area.component.ts:24 ERROR NullInjectorError: R3InjectorError(AppModule)[Flashcard ...

How to Use Conditional In-Line CSS for Internet Explorer and Other Browsers

After inspecting the source code for this website, I noticed a cool feature where the page changes based on your scrolling position. It creates a visually appealing effect. Upon further examination of the source in FireFox, I observed the use of -webkit-t ...

``If you're looking to retrieve, modify, and display information in your Vue application with the help of

I'm facing an issue where I am trying to retrieve data using the axios get request and then updating it based on the response of another axios get request. However, I am unable to display the data from the second request. The following is a snippet o ...

Using PHP to calculate the total number of records within an HTML document

I am currently working on a PHP script to establish a connection with my MySQL database in order to retrieve the total number of users registered on my forum by counting the records in the table. https://i.sstatic.net/ZR0IY.png The PHP script should disp ...

I desire for it to effortlessly unlock within my matmenu as soon as the webpage loads

Upon opening my page, I want the material menu to automatically open. However, since there is no click action, I am encountering an error stating that "trigger" is undefined. An error occurred: TypeError: Cannot read properties of undefined (reading &apo ...

The element is assumed to have an 'any' type due to the index expression not being of type 'number'. - Error in Index Signature

I've recently started using TypeScript and encountered the following issue: Element implicitly has an 'any' type because index expression is not of type 'number' This error message appears on this line --> const { status, msg ...

Proper method of retrieving a property as a designated type within a union type

I have a scenario where I need to return a specific property from a function in various parts of an application. This property can fall into one of two categories, each with string literal properties. One category is an extension of the other. How can I ...

Tips for deploying an Angular application with Node.js

Currently, I've set up a nodejs backend by following a tutorial to integrate tweets into the frontend of my application. As I prepare to deploy to a development server, I have successfully built the frontend using ng build --prod. However, I am facin ...

What is the best method for implementing pagination in Larvael with React using Inertia?

Is there a way to paginate in react using inertia with laravel? When pulling paginated data, I use the following code: $contacts = Contact::orderBy('name', 'asc')->paginate(10); return Inertia::render('Contacts/index', [ ...

Incorporating JavaScript/JSON into your Ebay listings to seamlessly receive user-selected choices

There has been a trend among Ebay users to incorporate dynamic data fetching and sending from external sources in their listings. This could be for implementing a shipping calculator or offering different product variants through dropdown lists. You can c ...

I am experiencing an issue where the tooltip does not appear when I click the icon. What adjustments can be made to the code to ensure that the tooltip

I have created a feature to copy abbreviation definitions when the clipboard icon is clicked. A tooltip displaying 'Copied' should appear after clicking the icon, but for some reason, it's not visible. Here's the code: $(document).re ...

Count the number of URL segments using JavaScript and jQuery

Can anyone suggest an efficient method to count the number of segments in a URL using JavaScript/jQuery? For instance: www.myexampleurl.com/section1/section2/section3 should output 3 ...

The exportAs property for matAutocomplete has not been specified

Issue Detected An error occurred with the directive "exportAs" set to "matAutocomplete" ("-label="Number" matInput [formControl]="myControl" [matAutocomplete]="auto"> I implemented code referenced from https://material.angular.io/components/auto ...