forked from swiftwasm/JavaScriptKit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathClosureAsyncAPIs.swift
More file actions
74 lines (61 loc) · 2.2 KB
/
ClosureAsyncAPIs.swift
File metadata and controls
74 lines (61 loc) · 2.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import XCTest
import JavaScriptKit
import JavaScriptEventLoop
// MARK: - Direction A: Swift awaits a JS async callback
@JS func awaitAsyncCallback(_ fetch: (String) async throws(JSException) -> String) async throws(JSException) -> String {
let resolved = try await fetch("request")
return "swift-saw:\(resolved)"
}
// MARK: - Direction B: a Swift async closure handed to JS
@JS func makeAsyncParser() -> JSTypedClosure<(String) async throws(JSException) -> String> {
return JSTypedClosure { (text: String) async throws(JSException) -> String in
await Task.yield()
guard let value = Int(text) else {
throw JSException(JSError(message: "AsyncParseError: \(text)").jsValue)
}
return "parsed:\(value)"
}
}
@JS func makeAsyncEcho() -> JSTypedClosure<(String) async -> String> {
return JSTypedClosure { (text: String) async -> String in
await Task.yield()
return "echo:\(text)"
}
}
@JS func makeAsyncRecorder() -> JSTypedClosure<(String) async throws(JSException) -> Void> {
return JSTypedClosure { (text: String) async throws(JSException) -> Void in
await Task.yield()
if text == "boom" {
throw JSException(JSError(message: "AsyncRecorderError").jsValue)
}
AsyncRecorderState.lastRecorded = text
}
}
@JS func lastRecordedValue() -> String {
return AsyncRecorderState.lastRecorded
}
@JS func asyncThrowsClosureRejectSupported() -> Bool {
#if compiler(>=6.3)
return true
#else
return false
#endif
}
@JS func makeAsyncPointMaker() -> JSTypedClosure<(Double) async -> DataPoint> {
return JSTypedClosure { (seed: Double) async -> DataPoint in
await Task.yield()
return DataPoint(x: seed, y: seed * 2, label: "async:\(seed)", optCount: nil, optFlag: nil)
}
}
enum AsyncRecorderState {
nonisolated(unsafe) static var lastRecorded: String = ""
}
// MARK: - XCTest entry point
final class ClosureAsyncTests: XCTestCase {
func testRunJsClosureAsyncTests() async throws {
try await ClosureAsyncImports.runJsClosureAsyncTests()
}
}
@JSClass struct ClosureAsyncImports {
@JSFunction static func runJsClosureAsyncTests() async throws(JSException)
}