Promises implementation in TypeScript and async/await

In this article, we learn how to promise work when we use promises in our application. A promise is a TypeScript object which is used to write asynchronous programs for our application. The promises are a better choice when we managing multiple asynchronous operations with error handling code for good readability.

Asynchronous program: It allows us to move to the next line of code before the previous task is completed. so we could not wait until the process is done.

To create a promise, we use new Promise(executor) syntax and provide an executor function as an argument. This executor function provides a means to control the behavior of our promise resolution or rejection.

var promise = new Promise(function(resolve, reject){
     // logic goes here

Promise Parameter

  • Promise accepts callback function as a parameter
  • That callback function accepts 2 parameter resolve and reject
  • When condition is true then it returns resolve else it returns the reject

Bleow is the diffrent states return by promise

Return Status Description
Fulfilled When promise operation executed successfully it reteun this status
Rejected When promise operation executed failed it reteun this status
Pending When promise operation is neither fulfilled nor rejected it return this status

Let’s take an example of findEven(number) in a promise which was created using the Promise constructor that resolves after 1 second. Display in below code.

//genrate random number
const getRandomInt = (): string => {
    return ( Math.random() * 10 ).toFixed( 0 );

//Promise we created.
const findEven = new Promise( ( resolve, reject ) => {
    setTimeout( function(): void {

        // convert `string` to `number`
        const value = parseInt( getRandomInt() );

        if( value % 2 === 0 ) {
            resolve( value );
        } else {
            reject( 'Odd number found : ' + value );
    }, 1000 );
} );

//lisner which we get
findEven.then( ( value ) => {
    // (parameter) value: number
    app2Div.innerHTML = 'Resolved:'+ (value );

} ).catch( ( error ) => {
    // (parameter) error: any
    app2Div.innerHTML = 'Rejected:'+ error;

} ).finally( () => {
   app3Div.innerHTML = 'Completed';

} );

In the above example, we create a Promise for finding an even number.
resolve state Its data-type of this promise is number, hence the TypeScript compiler won’t allow you to call resolve function with a value other than a value of type number.
reject stateIts data-type of this promise is the string we get in the “catch” error message to display the user.

Output Demo

Below is the demo code for the promises implementation.

Spread the love
  • 1
  • 2