Skip to content

Commit c538b1a

Browse files
Use Result-based continuation for JSRemote typed throws
Co-authored-by: Shelley <shelley@exe.dev>
1 parent a2f20b3 commit c538b1a

File tree

1 file changed

+7
-16
lines changed

1 file changed

+7
-16
lines changed

Sources/JavaScriptEventLoop/JSRemote.swift

Lines changed: 7 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -35,21 +35,11 @@ extension JSRemote where T == JSObject {
3535
public func withJSObject<R: Sendable, E: Error>(
3636
_ body: @Sendable @escaping (JSObject) throws(E) -> R
3737
) async throws(E) -> sending R {
38-
do {
39-
return try await _withJSObjectAnyError(body)
40-
} catch {
41-
throw error as! E
42-
}
43-
}
44-
45-
private func _withJSObjectAnyError<R: Sendable>(
46-
_ body: @Sendable @escaping (JSObject) throws(any Error) -> R
47-
) async throws -> sending R {
4838
#if _runtime(_multithreaded)
4939
if storage.sourceTid == swjs_get_worker_thread_id_cached() {
5040
return try body(storage.sourceObject)
5141
}
52-
return try await withCheckedThrowingContinuation { continuation in
42+
let result: Result<R, E> = await withCheckedContinuation { continuation in
5343
let context = _JSRemoteContext(
5444
sourceObject: storage.sourceObject,
5545
body: body,
@@ -60,6 +50,7 @@ extension JSRemote where T == JSObject {
6050
Unmanaged.passRetained(context).toOpaque()
6151
)
6252
}
53+
return try result.get()
6354
#else
6455
return try body(storage.sourceObject)
6556
#endif
@@ -95,17 +86,17 @@ private final class _JSRemoteContext: @unchecked Sendable {
9586
let invokeBody: () -> Bool
9687

9788
#if compiler(>=6.4)
98-
init<R: Sendable>(
89+
init<R: Sendable, E: Error>(
9990
sourceObject: JSObject,
100-
body: @escaping @Sendable (JSObject) throws(any Error) -> R,
101-
continuation: CheckedContinuation<R, any Error>
91+
body: @escaping @Sendable (JSObject) throws(E) -> R,
92+
continuation: CheckedContinuation<Result<R, E>, Never>
10293
) {
10394
self.invokeBody = {
10495
do {
105-
continuation.resume(returning: try body(sourceObject))
96+
continuation.resume(returning: .success(try body(sourceObject)))
10697
return false
10798
} catch {
108-
continuation.resume(throwing: error)
99+
continuation.resume(returning: .failure(error as! E))
109100
return true
110101
}
111102
}

0 commit comments

Comments
 (0)