EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login
Home Software Development Software Development Tutorials TypeScript Tutorial TypeScript promise type
Secondary Sidebar
TypeScript Tutorial
  • Type of Union
    • TypeScript Object Type
    • TypeScript type check
    • TypeScript promise type
    • TypeScript JSON type
    • TypeScript Union Types
    • TypeScript typeof
    • TypeScript Types
  • TypeScript Basic and Advanced
    • What is TypeScript?
    • Typescript Examples
    • TypeScript Versions
    • TypeScript Operators
    • JavaScript dump object
    • JavaScript get Method
    • Webpack ReactJS
    • Code Generator JavaScript
    • JavaScript Projects
    • Call Stack JavaScript
    • JavaScript Projects GitHub
    • JavaScript Filter Function
    • JavaScript nan
    • JavaScripttimestamp
    • TypeScript loop
    • CoffeeScript
    • TypeScript Webpack
    • setTimeout TypeScript
    • DHTMLX
    • CoffeeScript for loop
    • TypeScript number
    • JavaScript export module
    • TypeScript string contains
    • TypeScript Inheritance
    • TypeScript get
    • TypeScript undefined
    • TypeScript Global Variable
    • TypeScript Dictionary
    • TypeScript Generic
    • TypeScript Cast Object
    • TypeScript Optional Parameters
    • TypeScript? switch
    • TypeScript promise
    • TypeScript tuple
    • TypeScript Hashmap
    • TypeScript let
    • TypeScript Getter
    • TypeScript Pattern Matching
    • TypeScript number to string
    • TypeScript substring
    • TypeScript?lambda
    • TypeScript UUID
    • TypeScript JSDoc
    • TypeScript Decorators
    • Typescript for loop
    • TypeScript HTTP Request
    • TypeScript Abstract Class
    • TypeScript Question Mark
    • TypeScript Nullable
    • TypeScript reduce
    • TypeScript Mixins
    • TypeScript keyof
    • TypeScript string to number
    • TypeScript JSON parse
    • TypeScript const
    • TypeScript declare module
    • TypeScript String
    • TypeScript filter
    • TypeScript Multiple Constructors
    • TypeScript? Set
    • TypeScript string interpolation
    • TypeScript instanceof
    • TypeScript JSON
    • TypeScript Arrow Function
    • TypeScript generator
    • TypeScript namespace
    • TypeScript default parameter
    • TypeScript cast
    • TypeScript babel
    • Typescript Key-Value Pair
    • TypeScript if
    • TypeScript keyof Enum
    • TypeScript wait
    • TypeScript Optional Chaining
    • TypeScript JSX
    • TypeScript Version Check
    • TypeScript Unit Testing
    • TypeScript Handbook
    • TypeScript module
    • TypeScript Extend Interface
    • TypeScript npm
    • TypeScript pick
    • TypeScript Interface Default Value
    • JavaScript import module
    • Obfuscate Javascript
    • TypeScript basics
    • setInterval TypeScript
  • TypeScript Array
    • TypeScript Array of Objects
    • Methods TypeScript Array
    • TypeScript remove item from array
    • TypeScript add to array
    • TypeScript Array Contains
  • Function Of Array
    • TypeScript Function Interface
    • TypeScript Functions
    • TypeScript Export Function
    • TypeScript function return type

TypeScript promise type

TypeScript promise type

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
}

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

All in One Software Development Bundle(600+ Courses, 50+ projects)
Python TutorialC SharpJavaJavaScript
C Plus PlusSoftware TestingSQLKali Linux
Price
View Courses
600+ Online Courses | 50+ projects | 3000+ Hours | Verifiable Certificates | Lifetime Access
4.6 (86,818 ratings)

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:

TypeScript promise type output 1

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:

TypeScript promise type output 2

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:

output 3

The random number generated has given an odd number on computation, hence the result.

output 3.2

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

This is a guide to TypeScript promise type. Here we discuss How does TypeScript Promise type work along with the examples and outputs. You may also have a look at the following articles to learn more –

  1. Typescript for loop
  2. TypeScript let
  3. TypeScript typeof
  4. TypeScript Operators
0 Shares
Share
Tweet
Share
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2022 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Software Development Course

C# Programming, Conditional Constructs, Loops, Arrays, OOPS Concept

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more