Explain Typescript Promises to a Java Developer

In Typescript (and JavaScript), a Promise is an object that is used for representing the eventual completion or failure of an asynchronous operation. It’s similar Java Futures: both represents the result of an asynchronous computation that may not have completed yet.

A Promise has:

  1. a then method, which allows you to specify a callback function that will be called when the asynchronous operation completes successfully.

  2. a catch method that takes a callback that will be executed if the asynchronous operation fails.

Here’s an example of using a Promise in Typescript:

function getData(): Promise<string> {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve("running callback passed in the then() method");
    }, 1000);
  });
}

getData().then(data => {
  console.log(data);
}).catch(error => {
  console.error(error);
});

This outputs:

running callback passed in the then() method

In this example, the getData function returns a Promise that resolves after a 1 second delay. When it resolves, it executes the callback passed to the then(), calling it a string value: calling resolve to run the callback passed in the then() method. The callback function logs this value on the console.

If the Promise were rejected, the catch method would be called instead of then.

Let’s contrast this with Java and write the same code using CompletableFuture which has similar methods to then and catch:

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

public class Example {
  public static CompletableFuture<String> getData() {
    return CompletableFuture.supplyAsync(() -> {
      try {
        TimeUnit.SECONDS.sleep(1);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
      return "running callback passed in the thenAccept() method";
    });
  }

  public static void main(String[] args) {
    getData().thenAccept(data -> {
      System.out.println(data);
    }).exceptionally(error -> {
      error.printStackTrace();
      return null;
    });
  }
}

In the example above, the getData method returns a CompletableFuture that completes after a 1 second delay. The thenAccept method is called on the returned CompletableFuture and prints the value “running callback passed in the thenAccept() method”. If there were errors or any exceptions, he exceptionally method would be called instead and print the error stack trace.

Speak Your Mind