Updated April 7, 2023
Introduction to TypeScript promise type
TypeScript Promise type is a TypeScript object used to write Asynchronous programs. Promise is a good option when the user has to manage multiple Asynchronous operations, readability, and error handling. Asynchronous programming allows users to move to the next line in the code before completing the previous task or the previous line. Promise type is available in all the modern JavaScript Engines, which motivates users to bring in the Async style code or also known as callback style code. In this tutorial, we shall see what TypeScript Promise type is, how these Promises work, when is it to be used, and how to use it.
Syntax:
Here is the syntax of the Promise type,
var sample_promise = new Promise(function(resolve, reject) {
// body of the code
}
In TypeScript, promise type takes an inner function, which further accepts resolve and rejects as parameters.
Promise accepts a callback function as parameters, and in turn, the callback function accepts two other parameters, resolve and reject. If the condition is true, then resolve is returned; else, returns reject. Basically, the return type of Promise type is defined immediately after the keyword Promise.
How does TypeScript Promise type work?
One good thing about the Promise type is that it can understand the flow of values through the promise chain. Users can provide the data type of the value returned whenever the promise type is fulfilled.
- As the error returned by promise type can be of any type, the default data type of the promised type’s returned value is rejected is set to any in TypeScript.
- Generic type declaration is used to annotate the resolution value of the promise type.
- It has a Promise constructor in the form of a new Promise<Type> ( ), which indicates the resolved value of the promise type.
- TypeScript has Promise states:
pending: This state in Promise type refers to the first state when the promise is neither fulfilled nor rejected.
fulfilled: This state in Promise type refers to the promise operation being executed successfully.
rejected: This state in Promise type refers to the promise operation being failed.
Example #1
TypeScript promise type Timeout asynchronous function
var sample_promise = new Promise((resolve, reject) => {
setTimeout(() => {
console.log("This is an asynchronous call which has a timeout of 20 milli seconds!");
resolve();
}, 2000);
});
Output:
Here, we are working on a Promise type with two parameters and using it for an asynchronous function, which returns a message after 20 milliseconds.
Example #2
TypeScript promise type with a random number
const emp_promise = new Promise<boolean | string>((resolve, reject) => {
const pr_random_nm = Math.random() * 5;
if (pr_random_nm > 21) {
resolve(true);
return;
}
reject("pr_random_nm is less than 5");
});
emp_promise.catch(error => console.log("Error if any - ", error));
Output:
Here, Math.random() is a function that generates a random integer on every click. Hence, based on the random number generated, it is multiplied by 5, and the resultant is checked for a condition. If condition is satisfied, it returns resolve(true) else returns reject(“error”).
Here, did you just notice how to reject() is returning a string? This is because we have added a union in the declaration type of the Promise type, and hence both the return types of resolve and reject are acceptable here.
Example #3
TypeScript promise type, finding an even integer.
const get_random = (): string => {
return ( Math.random() * 10 ).toFixed( 0 );
};
// resolving with an `even` integer
const find_Even_integer = new Promise<number>( ( resolve, reject ) => {
setTimeout( function(): void {
// conversion of string to integer
const value_promise = parseInt( get_random() );
if( value_promise % 2 === 0 ) {
resolve( value_promise );
} else {
reject( 'We have encountered an odd number!' );
}
}, 2000 );
} );
// promise type
find_Even_integer.then( ( value_promise ) => {
console.log( 'If Resolved-1 or Resolved+1:', value_promise + 1 );
return `${ value_promise + 1 }`;
} ).then( ( value_promise ) => {
console.log( 'if Resolved-2:', value_promise + 1 );
} ).catch( ( error ) => {Promise.any
Promise.resolve
console.log( 'If Rejected:', error );
} ).finally( () => {
console.log( 'Promise type Completed!' );
} );
Output:
The random number generated has given an odd number on computation, hence the result.
As the number is generated is a random value, hence the other output based on computation.
Promise.resolve: It is a static method to resolve Promise calls, returns promise if successfully resolved with the value provided to resolve Promise.resolve(value). It is way much easier than the Promise call, adding logic to the call to resolve immediately.
Promise.reject: It is similar to Promies.resolve() method. It always returns a rejected promise type as Promise.reject( error ). This value of Promise rejections and type any and are taken from error argument.
Promise.all: In some of the scenarios, the user needs to deal with multiple numbers of Promises. In such cases, to execute the callback successfully with all the functions resolved, one needs to use Promise.all, also a static method.
Conclusion
In this article, we have seen what TypeScript promise type is and how is it written syntactically. Also have seen the various Promise parameters required and their usage in real coding scenarios. We have shown a few examples from a simple one to one complex example, which will help get a good idea of how Promise works for Asynchronous calls.
Recommended Articles
We hope that this EDUCBA information on “TypeScript promise type” was beneficial to you. You can view EDUCBA’s recommended articles for more information.