March 20, 2023

JavaScript - What is Promise

A promise object is an instance of the Promise class. It represents the eventual completion or failure of an asynchronous operation.

A Promise is kind of proxy for a value might be unknown when the promise is created. You can associate handlers with a promise to receive notification/result of success and failure of asynchronous operation performed by promise executor.

Promise executor is simply a function passed to the constructor of Promise class, it controls the behavior of promise's resolution (success )or rejection (failure).

Promise lets asynchronous methods return values like synchronous methods. Instead of immediately returning the final value, it returns a promise object as a mechanism to supply the value at some point in the future.

A Promise object can have one of these states:

  • pending: initial state (neither fulfilled nor rejected)
  • fulfilled: when the operation was completed successfully.
  • rejected: when the operation failed.

To create a promise, we use new Promise(executor) syntax and provide an executor function as an argument.

To consume a promise, we use .then() function to receive the result of promise.

The .then() method of the promise object takes up to two arguments:

  1. First argument is a callback function for the fulfilled case of the promise (usullay known as resolve)
  2. Second argument is a callback function for the rejected case (usullay known as reject).

An example:

let myPromise = new Promise(function(resolve, reject) {
    let status_code = 200;  //to call resolve/success
    //let status_code = 201; //to call reject/failure
  
    if (status_code == 200) {
      resolve("Status code is 200");
    } else {
      reject("Status code is not 200");
    }
  });
  
myPromise.then(
	function(value) {console.log("Success:", value);},
	function(error) {console.log("Error:", error);}
);

For this example, inside the Promise executor function, if the variable status_code value is 200 then it will call resolve handler of the promise, which ultimately fall in the fulfilled callback of .then() function.

If you change the status_code value to anything other than 200, then it will call reject handler of the promise, which ultimately fall in the rejected callback of .then() function.

References:

Related Post(s):

TypeScript - Promise only refers to a type, but is being used as a value

When using Promise in TypeScript code and transpiling, it generates the error:

'Promise' only refers to a type, but is being used as a value here. 
Do you need to change your target library? 
Try changing the 'lib' compiler option to es2015 or later

There could be following reasons/fixes for this issue:

  • Check in tsconfig.json file, if the target property (under compilerOptions) is set to es2015 or later (as suggested in the error message).
    {
        "compilerOptions": {
            "target": "es2015",
        }
    }
    
  • In tsconfig.json file, add lib property (under compilerOptions), and set it values to es2015 or later.
    {
        "compilerOptions": {
            "target": "es2015",
            "lib": ["dom", "es2015", "es5", "es6"],
        }
    }
    
  • A quick work around for this error is just removing the type check for Promise, rather than fixing it. Declar the Promise as a variable with type any.
    declare var Promise: any;
    
  • Try to install @types/node from npm;
    npm instal @types/node
    
  • Please be aware that if you are running the tsc command with a file name, then the compiler will ignore the tsconfig.json file. For example, transpiling the file like this:
    tsc myfile.ts
    
    You can edit the tsconfig.json to include a set of files with files property, e.g:
    {
        "compilerOptions": {
            "module": "commonjs",
            "noImplicitAny": true,
            "removeComments": true,
            "preserveConstEnums": true,
            "sourceMap": true,
            "target": "es2015",
            "lib": ["dom", "es2015", "es5", "es6"],
        },
        "files": [
            "myfile.ts",
            "service1.ts",
            "common.ts",
            "util.ts",
        ]
    }