TypeScript Promises Examples

By Digamber Rawat Last updated on
Today in this tutorial, we are going to understand what Promises are, how promise work, when should we use promises, and how to use promises properly. A promise is a TypeScript object which is used to write asynchronous programs. A promise is always a better choice when it comes to managing multiple asynchronous operations, error handling and better code readability. We know what does synchronous and asynchronous programs are. The asynchronous program allows us to move to the next line of code before the previous task is completed.

TypeScript Callback Example

Earlier, we used to be dependent on callback functions, but callbacks were not as flexible as promises are. Let’s understand how to execute the asynchronous task using the old school JavaScript callback method.

function asyncMethod(callBack) {
  setTimeout(() => {
    console.log("Async Callback");
    callBack();
  }, 1500);
}

asyncMethod(() => console.log("Async Callback Completed"));

In the above callback example, we declared a function and passed the callback parameter then inside the function, we set the setTimeout method and called the callback() method.

How to Create Promise?

A TypeScript promise takes inner function, and that inner function accepts resolve and rejects parameter. If we talk about Promise, so it works the same way we make promises to others. In a real-world scenario, when we make a promise to somebody that means the surety of doing something in the future. TypeScript promise holds the future value either it will return success or gets rejected.

You can see in the example below, how to define Promise, declare Promise with new operator instance and pass resolve and reject parameter within the inner function in the Promise object.

var promise = new Promise(function(resolve, reject){
     // code goes here
});

Understand TypeScript Promise Parameter:

  • A promise accepts callback function as a parameter.
  • Callback function accepts 2 parameter resolve and reject.
  • If condition is true then it returns resolve else it returns the reject.

What are Promise States:

State Description
pending This state refers to the first state when the promise is neither fulfilled nor rejected.
fulfilled As the name suggested when the promise operation executed successfully.
rejected This state refers to the state when the promise operation is failed.

TypeScript Promise Example

We inject inner function in Promise instance, and it works asynchronously as mentioned below:

var promise = new Promise((resolve, reject) => {
    setTimeout(() => {
      console.log("Async is done!");
      resolve();
    }, 1500);
});

It can also be wrapped around a custom function, like given below:

function asyncAction() {
  var promise = new Promise((resolve, reject) => {
    setTimeout(() => {
      console.log("Async is done!");
      resolve();
    }, 1500);
  });
  return promise;
}

Attach Success Handler with Promise

We can directly attach a success handler with Promise. As we know it takes 2 parameters one is for success and other is for failure. In the below example you can see how we are binding resolve with then method:

function asyncAction() {
  var promise = new Promise((resolve, reject) => {
    setTimeout(() => {
      console.log("Async is done!");
      resolve();
    }, 1500);
  });
  return promise;
}

asyncAction().then(
  () => console.log("Resolved!")
);

Attaching Error Handler with Promise

We can directly attach an error handler when promise gets rejected. It is known as reject function, check the following example how to attach error handler using catch() method with Promise:

function asyncAction() {
  var promise = new Promise((resolve, reject) => {
    setTimeout(() => {
      console.log("Async is done!");
      reject('Rejected!');
    }, 1500);
  });
  return promise;
}

asyncAction().then(function(success) { 
    console.log(success); 
}) 
.catch(function(error) { 
   // error handler is called
   console.log(error); 
});

Attach Multiple Then Handlers with Promise

We can attach multiple then handlers with Promise, this is known as chaining:

Promise.resolve("Completed")
  .then(
    (value) => {
      return 'Completed Two';
    },
    (error) => console.error(error)
  )
  .then(
    (value) => console.log(value),
    (error) => console.error(error)
  );

/*  Output:
   'Completed'
   'Completed Two'
*/

We don’t need to define error handler for every then method it will be a best practice if you pass the error handler within last then method.

Promise.reject('Rejected')
  .then(
    (value) => console.log(value)
   )
  .then(
    (value) => console.log(value),
    (error) => console.error(error)
  );

Conclusion

Promise offers an easy way to write asynchronous code instead of callbacks. Promises make developer’s life easy because promises are readable and come with excellent error handling supports.

Digamber Rawat
Digamber Rawat

Full stack developer with a passion for UI/UX design. I create beautiful and useful digital products to solve people’s problem and make their life easy.

Hire Me