它是如此簡單:我超熟悉Java completable期貨:
CompleteableFuture f = CompleteableFuture.supplyAsync(() -> "Hello").thenApply(s -> s.concat(" world"))
該代碼可以後跟:
CompleteableFuture word1 = f.thenApply(s -> s + " I am a completable future"); // "Hello world I am a completable future"
CompleteableFuture word2 = f.thenApply(s -> s + " I am teapot"); // "Hello world I am a teapot"
// option 1 (non blocking):
word1.thenAccept(System.out::println);
// option 2 (Blocking)
System.out.println(word1.get());
現在的Node.js:
const f = new Promise((resolve,reject) => {
return resolve('Hello')
}).then(s => " world")
const word1 = f.then(s => s + ' I am a promise') // 'Hello world I am a promise'
const word2 = f.then(s => s + ' I am a teapot') // 'Hello world I am a teapot'
// option 1 (non blocking)
word1.then(console.log)
// option 2 (Blocking)
console.log(word1.???????)
節點js的'option 2'在哪裏?沒有這個,我不得不創建一個閉包來更新一個簡單的值而不是返回。
我寧願有人說'你不知道你在說什麼',並告訴我,然後讓我的無知堅持下去。
node.js沒有辦法使非阻塞異步操作突然變爲阻塞和同步。它不這樣做。這是一個事件驅動的環境,幾乎所有的I/O都是非阻塞和異步的。要使用node.js環境,您可以使用它編程。而且,通過指定'p.then()'總是異步的。即使'p'已經解析,'.then()'處理程序總是會在事件循環的某個未來時刻被調用。 – jfriend00