FBLPromise+Async.m 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /**
  2. Copyright 2018 Google Inc. All rights reserved.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at:
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. #import "FBLPromise+Async.h"
  14. #import "FBLPromisePrivate.h"
  15. @implementation FBLPromise (AsyncAdditions)
  16. + (instancetype)async:(FBLPromiseAsyncWorkBlock)work {
  17. return [self onQueue:self.defaultDispatchQueue async:work];
  18. }
  19. + (instancetype)onQueue:(dispatch_queue_t)queue async:(FBLPromiseAsyncWorkBlock)work {
  20. NSParameterAssert(queue);
  21. NSParameterAssert(work);
  22. FBLPromise *promise = [[FBLPromise alloc] initPending];
  23. dispatch_group_async(FBLPromise.dispatchGroup, queue, ^{
  24. work(
  25. ^(id __nullable value) {
  26. if ([value isKindOfClass:[FBLPromise class]]) {
  27. [(FBLPromise *)value observeOnQueue:queue
  28. fulfill:^(id __nullable value) {
  29. [promise fulfill:value];
  30. }
  31. reject:^(NSError *error) {
  32. [promise reject:error];
  33. }];
  34. } else {
  35. [promise fulfill:value];
  36. }
  37. },
  38. ^(NSError *error) {
  39. [promise reject:error];
  40. });
  41. });
  42. return promise;
  43. }
  44. @end
  45. @implementation FBLPromise (DotSyntax_AsyncAdditions)
  46. + (FBLPromise* (^)(FBLPromiseAsyncWorkBlock))async {
  47. return ^(FBLPromiseAsyncWorkBlock work) {
  48. return [self async:work];
  49. };
  50. }
  51. + (FBLPromise* (^)(dispatch_queue_t, FBLPromiseAsyncWorkBlock))asyncOn {
  52. return ^(dispatch_queue_t queue, FBLPromiseAsyncWorkBlock work) {
  53. return [self onQueue:queue async:work];
  54. };
  55. }
  56. @end