Java Feature 和 JS Promise之间的关系,CompletableFuture相当于JS中的Promise,而Futrue中的get方法相当于JS中Promise的await关键字。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
final CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "1";
});

final ExecutorService executorService = Executors.newCachedThreadPool();
final Future<String> feture = executorService.submit(() -> {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "1";
});
future1.thenAccept(System.out::println);

System.out.println(feture.get());

future1.join();
executorService.shutdown();
1
2
3
4
5
6
7
8
9
10
11
new Promise((rs, rj) => {
setTimeout(()=>rs(1), 1000)
}).then(function(res){
console.log(res)
})

async function doWork() {
console.log(await new Promise((rs, rj) => setTimeout(()=>rs(1), 1000)))
}

doWork()