Merge pull request #1078 from RomanPodymov/master

Add AnyPromise.wait
This commit is contained in:
Max Howell 2019-06-28 10:23:21 -04:00 committed by GitHub
commit 2fdb8c64a8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 47 additions and 0 deletions

View File

@ -182,6 +182,13 @@ typedef void (^PMKResolver)(id __nullable) NS_REFINED_FOR_SWIFT;
*/
- (AnyPromise * __nonnull(^ __nonnull)(dispatch_queue_t __nonnull, dispatch_block_t __nonnull))ensureOn NS_REFINED_FOR_SWIFT;
/**
Wait until the promise is resolved.
@return Value if fulfilled or error if rejected.
*/
- (id __nullable)wait NS_REFINED_FOR_SWIFT;
/**
Create a new promise with an associated resolver.

View File

@ -112,6 +112,10 @@ NSString *const PMKErrorDomain = @"PMKErrorDomain";
};
}
- (id)wait {
return [d __wait];
}
- (BOOL)pending {
return [[d valueForKey:@"__pending"] boolValue];
}

View File

@ -61,6 +61,26 @@ import Foundation
}))
}
@objc public func __wait() -> Any? {
if Thread.isMainThread {
conf.logHandler(.waitOnMainThread)
}
var result = __value
if result == nil {
let group = DispatchGroup()
group.enter()
self.__pipe { obj in
result = obj
group.leave()
}
group.wait()
}
return result
}
/// Internal, do not use! Some behaviors undefined.
@objc public func __pipe(_ to: @escaping (Any?) -> Void) {
let to = { (obj: Any?) -> Void in

View File

@ -757,6 +757,22 @@ static inline AnyPromise *fulfillLater() {
[self waitForExpectationsWithTimeout:1 handler:nil];
}
- (void)test_61_wait_for_value {
id o = [AnyPromise promiseWithResolverBlock:^(PMKResolver resolve) {
resolve(@1);
}].wait;
XCTAssertEqualObjects(o, @1);
}
- (void)test_62_wait_for_error {
NSError* err = [AnyPromise promiseWithResolverBlock:^(PMKResolver resolve) {
resolve([NSError errorWithDomain:@"a" code:123 userInfo:nil]);
}].wait;
XCTAssertEqual(err.code, 123);
}
- (void)test_properties {
XCTAssertEqualObjects([AnyPromise promiseWithValue:@1].value, @1);
XCTAssertEqualObjects([[AnyPromise promiseWithValue:dummyWithCode(2)].value localizedDescription], @"2");