promise

The Promise is an object that represents either completion or failure of a user task. A promise in JavaScript can be in three states pending, fulfilled or rejected.
The main advantage of using a Promise in JavaScript is that a user can assign callback functions to the promises in case of a rejection or fulfillment of Promise. As the name suggests a promise is either kept or broken. So, a promise is either completed(kept) or rejected(broken).

Promise resolve() method:
Promise.resolve() method in JS returns a Promise object that is resolved with a given value. Any of the three things can happend:

  • If the value is a promise then promise is returned.
  • If the value has a “then” attached to the promise, then the returned promise will follow that “then” to till the final state.
  • The promise fulfilled with its value will be returned.
Syntax:
Promise.resolve(value);

Parameters:
Value to be resolved by this Promise.

Return Value:
Either the promise of the promise fulfilled with its value is returned.

Examples (with javascript):
<script> 
    var promise = Promise.resolve(17468); 
  
  promise.then(function(val) { 
        console.log(val); 
    }); 
//Output: 17468 
</script> 

… TypeScript

Let´s create a simple promise like this:

const one = new Promise<string>((resolve, reject) => {});

In this Promise,we used the promise constructor to take in string as the generic type for the Promise’s resolve value. The promise constructor takes an executor callback which the compiler will call by the runtime with these two arguments:

  • resolve — This is a function that is used to resolve the promise.
  • reject — This is a function that is used to reject the promise.

So, our promise can either be resolved, or rejected. The resolve part is taken care of by .then, and the reject part is taken care of by .catch.

one.then(value => {
  console.log('resolved', value);
});
one.catch(error => {
  console.log('rejected', error);
});

If we resolve a Promisethen callbacks are executed. Else, it means that the Promise is rejected and the catch callbacks are executed.

Promise resolutions are easy to write:

resolve('Hello')

Promise rejections on the other hand, should only be done in exceptional cases. It is considered as a bad practice to reject a promise with a raw string. Always use the error constructor new Error when rejecting a promise.

reject(new Error('failed'));

By Shabazz

Software Engineer, MCSD, Web developer & Angular specialist

Leave a Reply

Your email address will not be published. Required fields are marked *