Last Updated : 13 Jan, 2024
Summarize
Comments
Improve
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
: Theasync
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
). ReplaceReturnType
with the actual type of the resolved value.await
: Theawait
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 theasync
keyword to indicate that it is an asynchronous function. - Specify the Return Type as
Promise<T>
: Specify the return type of the function asPromise<T>
, whereT
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
async
function
exampleAsyncFunction(): Promise<string> {
return
"Hello, TypeScript!"
;
}
const a = exampleAsyncFunction();
console.log(a);
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!