@@ -30,6 +30,12 @@ public class JSOneshotClosure: JSObject, JSClosureProtocol {
3030 } )
3131 }
3232
33+ #if compiler(>=5.5)
34+ static func async ( _ body: @escaping ( [ JSValue ] ) async throws -> JSValue ) -> JSOneshotClosure {
35+ JSOneshotClosure ( makeAsyncClosure ( body) )
36+ }
37+ #endif
38+
3339 /// Release this function resource.
3440 /// After calling `release`, calling this function from JavaScript will fail.
3541 public func release( ) {
@@ -86,22 +92,7 @@ public class JSClosure: JSObject, JSClosureProtocol {
8692
8793 #if compiler(>=5.5)
8894 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- }
95+ JSClosure ( makeAsyncClosure ( body) )
10596 }
10697 #endif
10798
@@ -114,6 +105,25 @@ public class JSClosure: JSObject, JSClosureProtocol {
114105 #endif
115106}
116107
108+ private func makeAsyncClosure( _ body: @escaping ( [ JSValue ] ) async throws -> JSValue ) -> ( ( [ JSValue ] ) -> JSValue ) {
109+ { arguments in
110+ JSPromise { resolver in
111+ Task {
112+ do {
113+ let result = try await body ( arguments)
114+ resolver ( . success( result) )
115+ } catch {
116+ if let jsError = error as? JSError {
117+ resolver ( . failure( jsError. jsValue ( ) ) )
118+ } else {
119+ resolver ( . failure( JSError ( message: String ( describing: error) ) . jsValue ( ) ) )
120+ }
121+ }
122+ }
123+ } . jsValue ( )
124+ }
125+ }
126+
117127
118128// MARK: - `JSClosure` mechanism note
119129//
0 commit comments