The popularity of TypeScript is increasing very rapidly for frontend web development as well as backend web development. TypeScript is designed for the development of large applications and transpiles to JavaScript. As TypeScript is a superset of JavaScript, existing JavaScript programs are also valid TypeScript programs. TypeScript may be used to develop JavaScript applications for both client-side and server-side execution. If you are completely new to TypeScript for serverside(Node.js) then read this article to get the basic understanding of Typescript and how it can be used with Node.js
In this article, We will understand about promises in TypeScript and how we can make our code efficient after using promise in our TypeScript Code.
One way to program asynchronously is to use callbacks. We pass to an asynchronous function a function which it will call when the task is completed.
Let's understand with below example:
In the example above, A normal function is defined and an argument is passed which is a function and will be called once the task inside the function block is completed.
A promise is an object that may produce a single value sometime in the future: either a resolved value or a reason that it’s not resolved (e.g., a network error occurred). A promise may be in one of 3 possible states: fulfilled, rejected, or pending. Promise users can attach callbacks to handle the fulfilled value or the reason for rejection.
State of Promises
Inside the coding a promise condition is writen like below to return a valid promise.
A function returning promise can be handled easily like in below code:
We can also connect a series of then
handlers together in a chain, like in below example:
The promise is a very efficient way to write asynchronous code. Also, it solved all the problem occurred while working with callbacks.
Thank You!