Skip to content

Add async JSPromise.result property #200

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jul 19, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ func entrypoint() async throws {
resolve(.success(1))
})
try await expectEqual(p.value, 1)
try await expectEqual(p.result, .success(.number(1)))
}

try await asyncTest("await rejected Promise") {
Expand All @@ -41,6 +42,7 @@ func entrypoint() async throws {
let error = try await expectAsyncThrow(await p.value)
let jsValue = try expectCast(error, to: JSValue.self)
try expectEqual(jsValue, 3)
try await expectEqual(p.result, .failure(.number(3)))
}

try await asyncTest("Continuation") {
Expand Down
18 changes: 18 additions & 0 deletions Sources/JavaScriptEventLoop/JavaScriptEventLoop.swift
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,24 @@ public extension JSPromise {
}
}
}

/// Wait for the promise to complete, returning its result or exception as a Result.
var result: Result<JSValue, JSValue> {
get async {
await withUnsafeContinuation { [self] continuation in
self.then(
success: {
continuation.resume(returning: .success($0))
return JSValue.undefined
},
failure: {
continuation.resume(returning: .failure($0))
return JSValue.undefined
}
)
}
}
}
}

#endif