Skip to content

Commit d22292e

Browse files
committed
Add a JSClosure.async {} initializer
1 parent 9fbf0da commit d22292e

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

Sources/JavaScriptKit/FundamentalObjects/JSClosure.swift

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,27 @@ public class JSClosure: JSObject, JSClosureProtocol {
8484
Self.sharedClosures[hostFuncRef] = (self, body)
8585
}
8686

87+
#if compiler(>=5.5)
88+
static func async(_ body: @escaping ([JSValue]) async throws -> JSValue) -> JSClosure {
89+
JSClosure { arguments in
90+
JSPromise { resolver in
91+
Task {
92+
do {
93+
let result = try await body(arguments)
94+
resolver(.success(result))
95+
} catch {
96+
if let jsError = error as? JSError {
97+
resolver(.failure(jsError.jsValue()))
98+
} else {
99+
resolver(.failure(JSError(message: String(describing: error)).jsValue()))
100+
}
101+
}
102+
}
103+
}.jsValue()
104+
}
105+
}
106+
#endif
107+
87108
#if JAVASCRIPTKIT_WITHOUT_WEAKREFS
88109
deinit {
89110
guard isReleased else {

0 commit comments

Comments
 (0)