How to use Typescript with native ES6 Promises?


In the ES6 version of ECMAScript, promises are introduced for the first time.

To use the ES6 promises in the TypeScript project, users need to modify the tsconfig.json file.

Add the below code inside the ‘compilerOptions’ object.

{
   "compilerOptions": {
      "target": "es6",
   }
}

Also, users can add ‘ES6’ inside the ‘lib’ property, as shown below.

{
   "compilerOptions": {
      "lib": [
         "es6",
         "dom"
      ],
   }
}

However, users can also use the later versions of ECMAScript as they support the native promises in TypeScript. For example, es7, es10, etc.

The native promises in the TypeScript mean promises created by Promise() constructor inside the TypeScript code. However, we can resolve the promises returned from any API request.

The promises can have the below three states.

  • Pending – It means the promise is not completed yet.

  • Fulfilled – It means the promise is completed successfully without any error.

  • Rejected – It means the promise is completed with error.

Syntax

Users can follow the syntax below to use the native promises in TypeScript.

const promise = new Promise((resolve, reject) => {
   
   // resolve or reject the promise
});
promise
.then(() => {
   
   // show results
})
.catch(() => {
   
   // show error
});

In the above syntax, we have created the promise using the Promise() constructor and handled the results and errors inside the then() and catch() blocks, respectively. Furthermore, 'T' represents the return type when the promise is fulfilled successfully.

Example 1 (Basic Promises)

In the example below, we will learn the basic use of the ES6 native promises in TypeScript. We have created the two promises named first_promise and second_promise. We have resolved the first_promise and rejected the second_promise.

Also, users can see that the return type of the promises is a string. As first_promise resolves successfully, execution control goes to the then() block, and as second_promise is rejected, execution control goes to the catch() block.

// resolving a promise
const first_promise = new Promise((res, rej) => {
   res("First promise resolved");
});
first_promise
.then((result: string) => {
   console.log(result);
})
.catch((err) => {
   console.log(err);
});

// rejecting a promise
const second_promise = new Promise((res, rej) => {
   rej("Second promise rejected");
});
second_promise
.then((result: string) => {
   console.log(result);
})
.catch((err) => {
   console.log(err);
});

On compiling, it will generate the following JavaScript code.

// resolving a promise
var first_promise = new Promise(function (res, rej) {
   res("First promise resolved");
});
first_promise
.then(function (result) {
   console.log(result);
})["catch"](function (err) { 
   console.log(err);
});

// rejecting a promise
var second_promise = new Promise(function (res, rej) {
   rej("Second promise rejected");
});
second_promise
.then(function (result) {
   console.log(result);
})["catch"](function (err) {
   console.log(err);
});

Example 2 (Nested Promises)

In the example below, we have demonstrated to use the nested promises. We have created the outer_promise using the new keyword and Promise() constructor. Inside the callback function of the outer_promise, we have created the new child promise and resolved the child promise.

In the output, users can observe that outer_promise is resolved successfully as child promise. If we reject the child promise, outer_promise also gets rejected.

// resolving a promise
const outer_promise = new Promise((res) => {
   res(
      new Promise((resChild) => {
         resChild("Child Promise Resolved");
      })
   );
});
outer_promise
.then((result: string) => {
      console.log(result);
})
.catch((err) => {
   console.log(err);
}); 

On compiling, it will generate the following JavaScript code.

// resolving a promise
var outer_promise = new Promise(function (res) {
   res(new Promise(function (resChild) {
      resChild("Child Promise Resolved");
   }));
});
outer_promise
.then(function (result) {
   console.log(result);
})["catch"](function (err) {
   console.log(err);
});

Example 3 (Chained Promises)

In the example below, we have demonstrated the chined promise in TypeScript. As the name suggests, it’s a chain of promises. Here, we return the numeric value when we resolve the numeric_promise.

We receive 10 as a result inside the then() block. After that, we multiply the result by 2 and return it. We can get the returned value from the first then() block inside the second then() block, and so on. Control directly goes to the catch() block if any error occurs.

In the output, users can observe that the result value doubles in every then() block.

// resolving a promise
const numeric_promise = new Promise((res) => {
   res(10);
});
numeric_promise
.then((result: number) => {
   console.log("The result in the first then() block is - " + result);
   return result * 2;
})
.then((result: number) => {
   console.log("The result in the second then() block is - " + result);
   return result * 2;
})
.then((result: number) => {
   console.log("The result in the third then() block is - " + result);
   return result * 2;
})
.then((result: number) => {
   console.log("The result in the fourth then() block is - " + result);
})
.catch((err) => {
   console.log(err);
}); 

On compiling, it will generate the following JavaScript code. resolving a promise

var numeric_promise = new Promise(function (res) {
   res(10);
});
numeric_promise
.then(function (result) {
   console.log("The result in the first then() block is - " + result);
   return result * 2;
})
.then(function (result) {
   console.log("The result in the second then() block is - " + result);
   return result * 2;
})
.then(function (result) {
   console.log("The result in the third then() block is - " + result);
   return result * 2;
})
.then(function (result) {
   console.log("The result in the fourth then() block is - " + result);
})["catch"](function (err) {
   console.log(err);
}); 

Users learned to use ES6 native promises in TypeScript. We learned to use nested promises and promise chaining, also. Generally, users get the promises as the response of API, and they need to solve them using the then() and catch() block.

Updated on: 06-Mar-2023

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements