You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

86 lines
2.7 KiB

5 years ago
  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+All.h"
  14. #import "FBLPromise+Async.h"
  15. #import "FBLPromisePrivate.h"
  16. @implementation FBLPromise (AllAdditions)
  17. + (FBLPromise<NSArray *> *)all:(NSArray *)promises {
  18. return [self onQueue:self.defaultDispatchQueue all:promises];
  19. }
  20. + (FBLPromise<NSArray *> *)onQueue:(dispatch_queue_t)queue all:(NSArray *)allPromises {
  21. NSParameterAssert(queue);
  22. NSParameterAssert(allPromises);
  23. if (allPromises.count == 0) {
  24. return [[FBLPromise alloc] initWithResolution:@[]];
  25. }
  26. NSMutableArray *promises = [allPromises mutableCopy];
  27. return [FBLPromise
  28. onQueue:queue
  29. async:^(FBLPromiseFulfillBlock fulfill, FBLPromiseRejectBlock reject) {
  30. for (NSUInteger i = 0; i < promises.count; ++i) {
  31. id promise = promises[i];
  32. if ([promise isKindOfClass:self]) {
  33. continue;
  34. } else if ([promise isKindOfClass:[NSError class]]) {
  35. reject(promise);
  36. return;
  37. } else {
  38. [promises replaceObjectAtIndex:i
  39. withObject:[[FBLPromise alloc] initWithResolution:promise]];
  40. }
  41. }
  42. for (FBLPromise *promise in promises) {
  43. [promise observeOnQueue:queue
  44. fulfill:^(id __unused _) {
  45. // Wait until all are fulfilled.
  46. for (FBLPromise *promise in promises) {
  47. if (!promise.isFulfilled) {
  48. return;
  49. }
  50. }
  51. // If called multiple times, only the first one affects the result.
  52. fulfill([promises valueForKey:NSStringFromSelector(@selector(value))]);
  53. }
  54. reject:^(NSError *error) {
  55. reject(error);
  56. }];
  57. }
  58. }];
  59. }
  60. @end
  61. @implementation FBLPromise (DotSyntax_AllAdditions)
  62. + (FBLPromise<NSArray *> * (^)(NSArray *))all {
  63. return ^(NSArray<FBLPromise *> *promises) {
  64. return [self all:promises];
  65. };
  66. }
  67. + (FBLPromise<NSArray *> * (^)(dispatch_queue_t, NSArray *))allOn {
  68. return ^(dispatch_queue_t queue, NSArray<FBLPromise *> *promises) {
  69. return [self onQueue:queue all:promises];
  70. };
  71. }
  72. @end