How to Type an Async Function in TypeScript ? - GeeksforGeeks (2024)

Last Updated : 13 Jan, 2024

Summarize

Comments

Improve

Suggest changes

Like Article

Like

Save

Report

To type an asynchronous function in TypeScript, you can use the Promise type to denote that the function returns a promise.

Syntax:

async function functionName(parameters: ParameterTypes): Promise<ReturnType> {
// Asynchronous logic here
return await someAsyncOperation(); // or any other asynchronous logic
}
  • async: The async keyword declares that the function is asynchronous.
  • functionName: Replace with the desired name of your asynchronous function.
  • parameters: Replace with the parameters your function takes, if any.
  • ParameterTypes: Replace with the actual types of your function parameters.
  • Promise<ReturnType>: Indicates that the function returns a promise with a specific type (ReturnType). Replace ReturnType with the actual type of the resolved value.
  • await: The await keyword is used inside the asynchronous function to pause execution until the promise is resolved. It is used in conjunction with asynchronous operations that return promises.

Approach:

  • Use async Keyword: Prefix the function declaration with the async keyword to indicate that it is an asynchronous function.
  • Specify the Return Type as Promise<T>: Specify the return type of the function as Promise<T>, where T is the type of the resolved value.

Example 1: We define an asynchronous function named exampleAsyncFunction. The function returns a promise (Promise<string>) that will eventually resolve into a string "Hello, TypeScript!". The use of async and Promise<string> ensures that the function is treated as asynchronous and is expected to return a promise containing a string.

Javascript

Output:

Promise { 'Hello, TypeScript!' }

Example 2: We declare an asynchronous function asyncFunctionWithParams that accepts two parameters: param1 of type number and param2 of type string. The function returns a promise (Promise<number>) that resolves to the result of an asynchronous operation, in this case, the sum of param1 and the length of param2. The use of async and Promise<number> indicates that the function is asynchronous and returns a promise containing a numeric value.

Javascript

async function asyncFunctionWithParams(param1: number,

param2: string): Promise<number> {

// Async logic here

return param1 + param2.length;

}

const a = asyncFunctionWithParams(4, "hello");

console.log(a);

Output:

Promise { 9 }

Example 3: The greetUser function simulates an asynchronous operation using await new Promise(resolve => setTimeout(resolve, 1000));. It then constructs a greeting string with the provided name. The constructed greeting is logged to the console using console.log. The function returns the greeting as a promise. Finally, we call the asynchronous function and handle the result .then() and potential errors using .catch().

Javascript

function GFGexample(fact, callback) {

let myFact = "GeeksforGeeks Is Awesome, " + fact;

callback(myFact); // 2

}

async function greetUser(name: string):

Promise<string> {

// Simulating an asynchronous

// operation with a delay

await new Promise(resolve =>

setTimeout(resolve, 1000));

const greeting: string = `Hello, ${name}!`;

console.log(greeting);

return greeting;

}

// Calling the asynchronous function

greetUser("John")

.then(result => {

console.log("Async Function Result:", result);

})

.catch(error => {

console.error("Error:", error);

});

function logFact(fact) {

console.log(fact);

}

GFGexample("Learning is easy since", logFact);

Output:

Hello, John!
Async Function Result: Hello, John!


How to Type an Async Function in TypeScript ? - GeeksforGeeks (2)

Improve

Please Login to comment...

How to Type an Async Function in TypeScript ? - GeeksforGeeks (2024)
Top Articles
TRC20 to BEP20 Bridge | How to convert USDT TRC20 to BEP20 - Core.allbridge.io
You are leaving TIME and will be automatically redirected to NextAdvisor in a moment.
888-490-1703
Irrationale Kitchen
Weve Got You Surrounded Meme
Rivals Northwestern
Kian And Jc Seatgeek Promo Code
Frontline Iep Direct Login
Choose the antonym of the given word- Rarely a) Hardly b) Frequentlyc) Definitelyd) Absolutely
San Diego Terminal 2 Parking Promo Code
Qmx Airport
888-747-2264
24 Hour Pawn Shop San Antonio
Does Gamestop Take Airpods
Erica Mena Net Worth Forbes
Osrs Broken Dragon Pickaxe
The Smiths’ 30 best songs
The Machine 2023 Showtimes Near Cinemark Melrose Park
Scammer phone number lookup. How to check if a phone number is a scam
selena gomez en ropa interior
Theophylline: MedlinePlus Drug Information
Jaguar XJ gebraucht kaufen bei AutoScout24
Otterbrook Goldens
Volkswagen For Sale Craigslist
HLS Fetch Download tools - Chrome Web Store
Hardest Game Unblocked Games
America First Credit Union Review 2024 | Bankrate
Wedding Dr Amy Hutcheson Married
Vmgma Patient Portal
Twitter Marcus Lemonis
Ll Flooring Locations
Movies123 Avatar 2
Texas Lottery Pick 3 Daily 4
Grown Ups - TV Tropes
Bedford Barbers Nyc
Where Is The Wps Button On My Verizon Wireless Router
Neos Urgent Care Springfield Ma
112-nieuws: brand in cel Nieuwegein | autobranden in Soest en Houten
The Victors Boards2Go
Kamzz Llc
NYC DOE Charter Office
Princessdk
How to Sell Cars on Craigslist: A Guide for Car Dealers | ACV Auctions
R/Sandiego
H'aanit's Third Chapter | Gamer Guides: Your ultimate sou...
0Gomovies: Free Malayalam, Tamil & Hindi Movies - UK Journal
Jeld Wen Egress Calculator
Hfboards Islanders
The Young And The Restless Spoilers Toni – Repeat Replay
Find The Markers Microwave Code
Latest Posts
Article information

Author: Otha Schamberger

Last Updated:

Views: 5703

Rating: 4.4 / 5 (75 voted)

Reviews: 82% of readers found this page helpful

Author information

Name: Otha Schamberger

Birthday: 1999-08-15

Address: Suite 490 606 Hammes Ferry, Carterhaven, IL 62290

Phone: +8557035444877

Job: Forward IT Agent

Hobby: Fishing, Flying, Jewelry making, Digital arts, Sand art, Parkour, tabletop games

Introduction: My name is Otha Schamberger, I am a vast, good, healthy, cheerful, energetic, gorgeous, magnificent person who loves writing and wants to share my knowledge and understanding with you.