FBLPromise+Do.m 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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+Do.h"
  14. #import "FBLPromisePrivate.h"
  15. @implementation FBLPromise (DoAdditions)
  16. + (instancetype)do:(FBLPromiseDoWorkBlock)work {
  17. return [self onQueue:self.defaultDispatchQueue do:work];
  18. }
  19. + (instancetype)onQueue:(dispatch_queue_t)queue do:(FBLPromiseDoWorkBlock)work {
  20. NSParameterAssert(queue);
  21. NSParameterAssert(work);
  22. FBLPromise *promise = [[FBLPromise alloc] initPending];
  23. dispatch_group_async(FBLPromise.dispatchGroup, queue, ^{
  24. id value = work();
  25. if ([value isKindOfClass:[FBLPromise class]]) {
  26. [(FBLPromise *)value observeOnQueue:queue
  27. fulfill:^(id __nullable value) {
  28. [promise fulfill:value];
  29. }
  30. reject:^(NSError *error) {
  31. [promise reject:error];
  32. }];
  33. } else {
  34. [promise fulfill:value];
  35. }
  36. });
  37. return promise;
  38. }
  39. @end
  40. @implementation FBLPromise (DotSyntax_DoAdditions)
  41. + (FBLPromise* (^)(dispatch_queue_t, FBLPromiseDoWorkBlock))doOn {
  42. return ^(dispatch_queue_t queue, FBLPromiseDoWorkBlock work) {
  43. return [self onQueue:queue do:work];
  44. };
  45. }
  46. @end