Skip to content

Commit 26e79ba

Browse files
committed
Add async/await example
1 parent 67c4fb8 commit 26e79ba

File tree

6 files changed

+10434
-1405
lines changed

6 files changed

+10434
-1405
lines changed

examples/async-await/async-await.kt

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
import kotlinx.coroutines.*
2+
import kotlin.system.*
3+
4+
suspend fun sumParallel(): Int = coroutineScope {
5+
val a = async { f(100, 1) }
6+
val b = async { f(200, 5) }
7+
a.await() + b.await()
8+
}
9+
10+
suspend fun f(v: Int, s: Int): Int {
11+
println("Fetching $v...")
12+
delay(s * 1000L)
13+
return v
14+
}
15+
16+
fun main() = runBlocking {
17+
val result = sumParallel()
18+
println(result)
19+
}

examples/async-await/async-await.rs

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
use tokio::time::{sleep, Duration};
2+
3+
async fn sum_parallel() -> u64 {
4+
let a_future = f(100, 1);
5+
let b_future = f(200, 5);
6+
let (a, b) = futures::join!(a_future, b_future);
7+
return a + b
8+
}
9+
10+
async fn f(v: u64, s: u64) -> u64 {
11+
println!("Fetching {v}...");
12+
// delay
13+
sleep(Duration::from_secs(s)).await;
14+
return v
15+
}
16+
17+
#[tokio::main]
18+
async fn main() {
19+
let result = sum_parallel().await;
20+
print!("{}", result)
21+
}
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
import Foundation
2+
3+
func sumParallel() async -> Int {
4+
async let a = f(100, 1)
5+
async let b = f(200, 5)
6+
return await a + b
7+
}
8+
9+
func f(_ v: Int, _ s: Int) async -> Int
10+
{
11+
print("Fetching \(v)...")
12+
// delay
13+
let ns = UInt64(s * 1_000_000_000)
14+
try! await Task.sleep(nanoseconds: ns)
15+
return v
16+
}
17+
18+
@main struct Main {
19+
static func main() async {
20+
let result = await sumParallel()
21+
print(result)
22+
}
23+
}

examples/async-await/async-await.ts

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
async function sumParallel() {
2+
const aPromise = f(100, 1);
3+
const bPromise = f(200, 5);
4+
const [a, b] = await Promise.all([
5+
aPromise,
6+
bPromise,
7+
]);
8+
return a + b;
9+
}
10+
11+
async function f(v: number, s: number) {
12+
console.log(`Fetching ${v}...`);
13+
// delay
14+
await new Promise((resolve) => {
15+
setTimeout(resolve, s * 1000);
16+
});
17+
return v;
18+
}
19+
20+
sumParallel().then(console.log);

0 commit comments

Comments
 (0)