Skip to content

Commit

Permalink
Add async JSPromise.result property (#200)
Browse files Browse the repository at this point in the history
  • Loading branch information
kateinoigakukun committed Jul 19, 2022
1 parent f1ef517 commit 901de66
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 0 deletions.
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

0 comments on commit 901de66

Please sign in to comment.