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
Secondary Sidebar
TypeScript Tutorial
  • 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
  • Type of Union
    • TypeScript Object Type
    • TypeScript type check
    • TypeScript promise type
    • TypeScript JSON type
    • TypeScript Union Types
    • TypeScript typeof
    • TypeScript Types
  • 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

TypeScript promise

Introduction to TypeScript promise

The promise in TypeScript is used to make asynchronous programming. The promise can be used when we want to handle multiple tasks at the same time. By the use of TypeScript promise, we can skip the current operation and move to the next line of the code. Promise provides the feature for asynchronous programming or parallel programming, which allows the number of tasks to be executed simultaneously at the same time. In the coming section, we will discuss more the promise in detail for better understanding.

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,950 ratings)

Syntax

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

As we discussed, a promise is used for parallel programming. It is an object available in TypeScript programming. Let’s see its syntax in detail for better understanding see below;

new Promise(function(resolve, reject){
// our logic goes here ..
});

As you can see in the above lines of syntax, we are using a new keyword to create the object of promise. This function has two parameters named reject and resolve. It also calls the callback function. We will see its internal working in more detail in the coming section and use it while programming.

How to implement promise in TypeScript?

As we know that promise in TypeScript is used to support parallel programming. Parallel programming is used when we want to execute a set of tasks simultaneously. The promise is used to handle multiple parallel calls. The main benefit of using the promise is that we can move to the next line of the code without executing the above line. This also helps us to increase the performance of the application.

Promise support in several states as well. In this section, we will look at the signature in detail also the return type, and the several states it supports for better understanding. See below;

1. new Promise(function(resolve, reject){

// logic goes here ..

});

In the above line of code, we are using the ‘new’ keyword to create the instance of the promise. As we already know that this is an object available in TypeScript. Also, it has one inner function, which has two parameters named ‘reject’ and ‘resolve’. Inside this function, we can pass a callback function.

2. Return type: It has two parameters inside the inner function. If the function’s response is a success, then it will return ‘resolve’; if the response from the function is not successful, it will return ‘reject’.

3. States available in promise of Typescript: Promise support several states. These states are used to get the status of the function. We have three different states available in the promise;

  • reject: If the response from the promise function fails, then the state would be ‘reject’.
  • pending: We the response does not come, and we are waiting for the result, then the state would be ‘pending’.
  • fulfilled: If the response forms the promise in TypeScript is received successfully, then the state would be ‘fullfeed’.

We can also perform and handle the success and error response, respectively. For this, we can use ‘reject’ and ‘resolve’ from the promise function only. In this section, we will cover how to handle the success and error in promise see below;

1. Handle error in the promise: We can easily handle the error response from a promise, for we have to reject parameter that we pass inside the callback function. This rejects parameter will handle the error; it will handle the error using the catch() block available. We can see one practice syntax for better understanding of its usage see below;

Example:

function demo() {
var promise = new Promise((resolve, reject) => {
// our logic goes here ..
reject();
}
demo().then(function(success) {
// success logic will go here  ..
})
.catch(function(error) {
// logic goes here  //
});

As you can see in the above lines of code, we are calling reject. This will handle the error and handle the exception using the catch block in the below line of code.

2. handle success in the promise: We can also handle the success response from the promise function. For this, we can use resolve and a success callback. Let’s see one sample syntax for a better understanding of the code for beginners see below;

Example:

function demo() {
var promise = new Promise((resolve, reject) => {
// logic will go here ..
resolve();
}
demo().then(
() => // logic goes here ..
);

In the above lines of code, we are calling the resolve function here; it will handle the success response from the promise function in TypeScript.

Examples

Here are the following example mention below

Example #1

In this example, we are trying to call the resolve function of promise, which will handle the successful response from the promise. This is a sample example for beginners to understand its usage.

Code:

// PROMISE-1
var mypromise = new Promise((resolve, reject) => {
console.log("Demo to show promise in Typescript !!");
resolve(100);
});
mypromise.then((val) => val + 200)
.then((val) => console.log("Value form the promse function is " + val)
.catch((err) => console.log("inside error block " + err)));

Output:

TypeScript promise output 1

Example #2

In this example, we are handling the error response from the promise in Typescript, a sample example for beginners.

Code:

// PROMISE-1
var mypromise = new Promise((resolve, reject) => {
console.log("Demo to show promise in Typescript !!");
reject("this is an reject response form the promise !!!!");
});
mypromise.then((val) => val)
.then((val) => console.log("Value form the promse function is " + val)
.catch((err) => console.log("inside error block " + err)));

Output:

TypeScript promise output 2

Rules and regulation for the promise

1. This is used to make asynchrony calls.

2. keep in mind that only tasks that are not dependent on each other can be called from. Otherwise, the data inconsistent issue will occur.

3. Need to pass inner function while using it; otherwise, the error will occur.

Conclusion

By using promise in TypeScript, we can easily implement parallel programming, which is very easy to read and understand. Also, by the use of it, we can execute multiple tasks at the same time; this can also increase the application performance. The only task which is not dependent on each other can be asynchrony.

Recommended Articles

This is a guide to TypeScript promise. Here we discuss How to implement promise in TypeScript and Examples along with the codes and outputs. You may also have a look at the following articles to learn more –

  1. TypeScript Versions
  2. TypeScript Array
  3. TypeScript Functions
  4. What is TypeScript?
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