From Java to JavaScript — Callback and Promise

Callbacks and asynchronous code in Java

Synchronous Java Example

interface ISomeEventListener {
void someEvent();
}
class SynchronousExample {
private ISomeEventListener someEventListener;
public void setSomeEventListener(ISomeEventListener someEventListener) {
this.someEventListener = someEventListener;
}
public void doSomeHeavyCalculation(final long howLongInMs) {
System.out.println("Doing some heavy work...");
// some heavy work...
try {
Thread.sleep(howLongInMs);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (this.someEventListener != null) {
someEventListener.someEvent();
}
}
public static void main(String[] args) {
final SynchronousExample example = new SynchronousExample();
example.setSomeEventListener(() -> {
System.out.println("Received some event!");
});
example.doSomeHeavyCalculation(1000);
}
}
example.setSomeEventListener(new ISomeEventListener() {
@Override
public void someEvent() {
System.out.println("Received some event!");
}
});

Asynchronous Java Example

class AsynchronousExample {
private ISomeEventListener someEventListener;
public void setSomeEventListener(ISomeEventListener someEventListener) {
this.someEventListener = someEventListener;
}
public void doSomeHeavyCalculation(final long howLongInMs) {
// some heavy work...
new Thread(() -> {
try {
System.out.println("Doing some heavy work...");
Thread.sleep(howLongInMs);
} catch (InterruptedException e) {
e.printStackTrace();
}

if (this.someEventListener != null) {
someEventListener.someEvent();
}
}).start();
}
public static void main(String[] args) {
final AsynchronousExample example = new AsynchronousExample();
example.setSomeEventListener(() -> {
System.out.println("Received some event!");
});
example.doSomeHeavyCalculation(1000);
}
}

Callbacks and asynchronous code in JavaScript

const id = setInterval(() => console.log('do something'), 5000);
clearInterval(id); //...when finished
const fetch = require("node-fetch"); // npm install node-fetchconst getSomeData = async () => {
try {
const response = await fetch('https://swapi.co/api/people/?search=r2');
if (response.ok) {
return await response.json();
} else {
throw response.status;
}
} catch (error) {
throw error;
}
}
getSomeData()
.then(json => console.log(json.results[0].name))
.catch(error => console.error(error))

React Native Mobile Developer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store