Akash Deep Vishwakarma
2 min readNov 9, 2023

--

What is 'Promise' in TypeScript?

Promise in TypeScript
  • A Promise in TypeScript is an object that represents an operation that hasn’t completed yet but is expected in the future.
  • It is a way to handle asynchronous operations.
  • When you create a Promise, you give it a function that will be executed when the operation is complete.
  • Promises can be used to make asynchronous requests to APIs, load data from files, or perform other tasks that take time to complete.
  • To create a Promise in TypeScript, you use the new Promise() constructor.
  • The constructor takes a function as an argument. This function will be executed when the operation is complete.
  • The function will take two parameters: resolve and reject.
  • If the operation succeeds, you call resolve() with the result of the operation. If the operation fails, you call reject() with the error that occurred.

Example:

const promise = new Promise((resolve, reject) => {
// Do something asynchronous
if (success) {
resolve('success');
} else {
reject('error');
}
});

  • Once you have created a Promise, you can use it to handle the asynchronous operation. For example, you can use the then() method to handle the success case, and the catch() method to handle the error case.

Example:

promise.then((result) => {
// Do something with the result
console.log(result);
}).catch((error) => {
// Do something with the error
console.log(error);
});

  • When we want to execute multiple tasks simultaneously then we should go for Promise.
  • States in Promise are -
    Rejected ❌
    Pending 🔄
    Fulfilled ✅
  • Only non-dependent tasks can be used with Promise otherwise, data inconsistency can happen.
  • Need to pass inner function otherwise it will result to an error.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Akash Deep Vishwakarma
Akash Deep Vishwakarma

Written by Akash Deep Vishwakarma

Specialist Programmer (SDE) @ Infosys | Java | Kotlin | TypeScript | Angular | Spring | Spring Boot | Android Developer

No responses yet

Write a response