forked from swiftwasm/JavaScriptKit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJSPromise.swift
More file actions
222 lines (201 loc) · 8.86 KB
/
JSPromise.swift
File metadata and controls
222 lines (201 loc) · 8.86 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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
#if hasFeature(Embedded) && os(WASI)
import _Concurrency
#endif
/// A wrapper around [the JavaScript `Promise` class](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)
public final class JSPromise: JSBridgedClass {
/// The underlying JavaScript `Promise` object.
public let jsObject: JSObject
/// The underlying JavaScript `Promise` object wrapped as `JSValue`.
public func jsValue() -> JSValue {
.object(jsObject)
}
public static var constructor: JSFunction? {
JSObject.global.Promise.function!
}
/// This private initializer assumes that the passed object is a JavaScript `Promise`
public init(unsafelyWrapping object: JSObject) {
jsObject = object
}
/// Creates a new `JSPromise` instance from a given JavaScript `Promise` object. If `jsObject`
/// is not an instance of JavaScript `Promise`, this initializer will return `nil`.
public convenience init?(_ jsObject: JSObject) {
self.init(from: jsObject)
}
/// Creates a new `JSPromise` instance from a given JavaScript `Promise` object. If `value`
/// is not an object and is not an instance of JavaScript `Promise`, this function will
/// return `nil`.
public static func construct(from value: JSValue) -> Self? {
guard case .object(let jsObject) = value else { return nil }
return Self(jsObject)
}
/// The result of a promise.
public enum Result: Equatable {
/// The promise resolved with a value.
case success(JSValue)
/// The promise rejected with a value.
case failure(JSValue)
}
/// Creates a new `JSPromise` instance from a given `resolver` closure.
/// The closure is passed a completion handler. Passing a successful
/// `Result` to the completion handler will cause the promise to resolve
/// with the corresponding value; passing a failure `Result` will cause the
/// promise to reject with the corresponding value.
/// Calling the completion handler more than once will have no effect
/// (per the JavaScript specification).
public convenience init(resolver: @escaping (@escaping (Result) -> Void) -> Void) {
let closure = JSOneshotClosure { arguments in
// The arguments are always coming from the `Promise` constructor, so we should be
// safe to assume their type here
let resolve = arguments[0].function!
let reject = arguments[1].function!
resolver {
switch $0 {
case .success(let success):
resolve(success)
case .failure(let error):
reject(error)
}
}
return .undefined
}
self.init(unsafelyWrapping: Self.constructor!.new(closure))
}
#if compiler(>=5.5) && (!hasFeature(Embedded) || os(WASI))
/// Creates a new `JSPromise` instance from a given async closure.
///
/// - Parameter body: The async closure to execute.
/// - Returns: A new `JSPromise` instance.
public static func async(body: @escaping @isolated(any) () async throws(JSException) -> Void) -> JSPromise {
self.async { () throws(JSException) -> JSValue in
try await body()
return .undefined
}
}
/// Creates a new `JSPromise` instance from a given async closure.
///
/// - Parameter body: The async closure to execute.
/// - Returns: A new `JSPromise` instance.
public static func async(body: @escaping @isolated(any) () async throws(JSException) -> JSValue) -> JSPromise {
JSPromise { resolver in
// NOTE: The context is fully transferred to the unstructured task
// isolation but the compiler can't prove it yet, so we need to
// use `@unchecked Sendable` to make it compile with the Swift 6 mode.
struct Context: @unchecked Sendable {
let resolver: (JSPromise.Result) -> Void
let body: () async throws(JSException) -> JSValue
}
let context = Context(resolver: resolver, body: body)
Task {
do throws(JSException) {
let result = try await context.body()
context.resolver(.success(result))
} catch {
context.resolver(.failure(error.thrownValue))
}
}
}
}
#endif
#if !hasFeature(Embedded)
public static func resolve(_ value: ConvertibleToJSValue) -> JSPromise {
self.init(unsafelyWrapping: Self.constructor!.resolve!(value).object!)
}
public static func reject(_ reason: ConvertibleToJSValue) -> JSPromise {
self.init(unsafelyWrapping: Self.constructor!.reject!(reason).object!)
}
#else
public static func resolve(_ value: some ConvertibleToJSValue) -> JSPromise {
self.init(unsafelyWrapping: constructor!.resolve!(value).object!)
}
public static func reject(_ reason: some ConvertibleToJSValue) -> JSPromise {
self.init(unsafelyWrapping: constructor!.reject!(reason).object!)
}
#endif
/// Schedules the `success` closure to be invoked on successful completion of `self`.
@discardableResult
public func then(success: @escaping (JSValue) -> JSValue) -> JSPromise {
let closure = JSOneshotClosure {
success($0[0]).jsValue
}
return JSPromise(unsafelyWrapping: jsObject.then!(closure).object!)
}
#if compiler(>=5.5) && (!hasFeature(Embedded) || os(WASI))
/// Schedules the `success` closure to be invoked on successful completion of `self`.
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
@discardableResult
public func then(
success: sending @escaping (sending JSValue) async throws(JSException) -> JSValue
) -> JSPromise {
let closure = JSOneshotClosure.async { arguments throws(JSException) -> JSValue in
return try await success(arguments[0])
}
return JSPromise(unsafelyWrapping: jsObject.then!(closure).object!)
}
#endif
/// Schedules the `success` closure to be invoked on successful completion of `self`.
@discardableResult
public func then(
success: @escaping (sending JSValue) -> JSValue,
failure: @escaping (sending JSValue) -> JSValue
) -> JSPromise {
let successClosure = JSOneshotClosure {
success($0[0]).jsValue
}
let failureClosure = JSOneshotClosure {
failure($0[0]).jsValue
}
return JSPromise(unsafelyWrapping: jsObject.then!(successClosure, failureClosure).object!)
}
#if compiler(>=5.5) && (!hasFeature(Embedded) || os(WASI))
/// Schedules the `success` closure to be invoked on successful completion of `self`.
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
@discardableResult
public func then(
success: sending @escaping (sending JSValue) async throws(JSException) -> JSValue,
failure: sending @escaping (sending JSValue) async throws(JSException) -> JSValue
) -> JSPromise {
let successClosure = JSOneshotClosure.async { arguments throws(JSException) -> JSValue in
try await success(arguments[0]).jsValue
}
let failureClosure = JSOneshotClosure.async { arguments throws(JSException) -> JSValue in
try await failure(arguments[0]).jsValue
}
return JSPromise(unsafelyWrapping: jsObject.then!(successClosure, failureClosure).object!)
}
#endif
/// Schedules the `failure` closure to be invoked on rejected completion of `self`.
@discardableResult
public func `catch`(
failure: @escaping (sending JSValue) -> JSValue
)
-> JSPromise
{
let closure = JSOneshotClosure {
failure($0[0]).jsValue
}
return .init(unsafelyWrapping: jsObject.catch!(closure).object!)
}
#if compiler(>=5.5) && (!hasFeature(Embedded) || os(WASI))
/// Schedules the `failure` closure to be invoked on rejected completion of `self`.
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
@discardableResult
public func `catch`(
failure: sending @escaping (sending JSValue) async throws(JSException) -> JSValue
) -> JSPromise {
let closure = JSOneshotClosure.async { arguments throws(JSException) -> JSValue in
try await failure(arguments[0]).jsValue
}
return .init(unsafelyWrapping: jsObject.catch!(closure).object!)
}
#endif
/// Schedules the `failure` closure to be invoked on either successful or rejected
/// completion of `self`.
@discardableResult
public func finally(successOrFailure: @escaping () -> Void) -> JSPromise {
let closure = JSOneshotClosure { _ in
successOrFailure()
return .undefined
}
return .init(unsafelyWrapping: jsObject.finally!(closure).object!)
}
}