Repository: mxcl/PromiseKit Branch: master Commit: 8c0734982392 Files: 135 Total size: 544.2 KB Directory structure: gitextract_8yos49k1/ ├── .github/ │ ├── FUNDING.yml │ ├── ISSUE_TEMPLATE.md │ ├── LinuxMain.stencil │ ├── codecov.yml │ ├── jazzy.yml │ ├── ranger.yml │ ├── sourcery.yml │ └── workflows/ │ ├── cd.yml │ ├── ci-podspec.yml │ ├── ci.yml │ └── publish.yml ├── .gitignore ├── .gitmodules ├── .tidelift.yml ├── .travis.yml ├── Documentation/ │ ├── Appendix.md │ ├── CommonPatterns.md │ ├── Examples/ │ │ ├── ImageCache.md │ │ ├── URLSession+BadResponseErrors.swift │ │ └── detweet.swift │ ├── FAQ.md │ ├── GettingStarted.md │ ├── Installation.md │ ├── ObjectiveC.md │ ├── README.md │ └── Troubleshooting.md ├── LICENSE ├── Package.swift ├── Package@swift-4.2.swift ├── Package@swift-5.0.swift ├── Package@swift-5.3.swift ├── PromiseKit.playground/ │ ├── Contents.swift │ ├── contents.xcplayground │ └── playground.xcworkspace/ │ └── contents.xcworkspacedata ├── PromiseKit.podspec ├── PromiseKit.xcodeproj/ │ ├── project.pbxproj │ ├── project.xcworkspace/ │ │ ├── contents.xcworkspacedata │ │ └── xcshareddata/ │ │ ├── IDEWorkspaceChecks.plist │ │ └── WorkspaceSettings.xcsettings │ └── xcshareddata/ │ └── xcschemes/ │ └── PromiseKit.xcscheme ├── README.md ├── Sources/ │ ├── AnyPromise+Private.h │ ├── AnyPromise.h │ ├── AnyPromise.m │ ├── AnyPromise.swift │ ├── Async.swift │ ├── Box.swift │ ├── Catchable.swift │ ├── Combine.swift │ ├── Configuration.swift │ ├── CustomStringConvertible.swift │ ├── Deprecations.swift │ ├── Error.swift │ ├── Guarantee.swift │ ├── Info.plist │ ├── LogEvent.swift │ ├── NSMethodSignatureForBlock.m │ ├── PMKCallVariadicBlock.m │ ├── Promise.swift │ ├── PromiseKit.h │ ├── Resolver.swift │ ├── Resources/ │ │ └── PrivacyInfo.xcprivacy │ ├── Thenable.swift │ ├── after.m │ ├── after.swift │ ├── dispatch_promise.m │ ├── firstly.swift │ ├── fwd.h │ ├── hang.m │ ├── hang.swift │ ├── join.m │ ├── race.m │ ├── race.swift │ ├── when.m │ └── when.swift ├── Tests/ │ ├── A+/ │ │ ├── 0.0.0.swift │ │ ├── 2.1.2.swift │ │ ├── 2.1.3.swift │ │ ├── 2.2.2.swift │ │ ├── 2.2.3.swift │ │ ├── 2.2.4.swift │ │ ├── 2.2.6.swift │ │ ├── 2.2.7.swift │ │ ├── 2.3.1.swift │ │ ├── 2.3.2.swift │ │ ├── 2.3.4.swift │ │ ├── README.md │ │ └── XCTestManifests.swift │ ├── Bridging/ │ │ ├── BridgingTests.m │ │ ├── BridgingTests.swift │ │ ├── Infrastructure.h │ │ ├── Infrastructure.m │ │ └── Infrastructure.swift │ ├── CoreObjC/ │ │ ├── AnyPromiseTests.m │ │ ├── AnyPromiseTests.swift │ │ ├── HangTests.m │ │ ├── JoinTests.m │ │ ├── PMKManifoldTests.m │ │ ├── RaceTests.m │ │ └── WhenTests.m │ ├── CorePromise/ │ │ ├── AfterTests.swift │ │ ├── AsyncTests.swift │ │ ├── CancellableErrorTests.swift │ │ ├── CatchableTests.swift │ │ ├── CombineTests.swift │ │ ├── DefaultDispatchQueueTests.swift │ │ ├── ErrorTests.swift │ │ ├── GuaranteeTests.swift │ │ ├── HangTests.swift │ │ ├── LoggingTests.swift │ │ ├── PromiseTests.swift │ │ ├── RaceTests.swift │ │ ├── RegressionTests.swift │ │ ├── ResolverTests.swift │ │ ├── StressTests.swift │ │ ├── ThenableTests.swift │ │ ├── Utilities.swift │ │ ├── WhenConcurrentTests.swift │ │ ├── WhenResolvedTests.swift │ │ ├── WhenTests.swift │ │ ├── XCTestManifests.swift │ │ └── ZalgoTests.swift │ ├── DeprecationTests.swift │ ├── JS-A+/ │ │ ├── .gitignore │ │ ├── AllTests.swift │ │ ├── JSAdapter.swift │ │ ├── JSPromise.swift │ │ ├── JSUtils.swift │ │ ├── MockNodeEnvironment.swift │ │ ├── README.md │ │ ├── index.js │ │ ├── package.json │ │ └── webpack.config.js │ └── LinuxMain.swift └── tea.yaml ================================================ FILE CONTENTS ================================================ ================================================ FILE: .github/FUNDING.yml ================================================ tidelift: "cocoapods/PromiseKit" patreon: "mxcl" github: mxcl ================================================ FILE: .github/ISSUE_TEMPLATE.md ================================================ [PLEASE READ THE TROUBLESHOOTING GUIDE](https://github.com/mxcl/PromiseKit/blob/master/Documentation/Troubleshooting.md). --- You read the guide but it didn’t help? OK, we’re here to help. * Please specify the PromiseKit major version you are using * [Please format your code in triple backticks and ensure readable indentation](https://help.github.com/articles/creating-and-highlighting-code-blocks/) * Please specify how you installed PromiseKit, ie. Carthage, CocoaPods, SwiftPM or other. If other provide DETAILED information about how you are integrating PromiseKit. If you ignore this template we will close your ticket and link to this template until you provide this necessary information. We cannot help you without it. ================================================ FILE: .github/LinuxMain.stencil ================================================ @testable import Core @testable import A_ import XCTest //TODO get this to run on CI and don’t have it committed //NOTE problem is Sourcery doesn’t support Linux currently //USAGE: cd PromiseKit/Sources/.. && sourcery --config .github/sourcery.yml {% for type in types.classes|based:"XCTestCase" %} extension {{ type.name }} { static var allTests = [ {% for method in type.methods %}{% if method.parameters.count == 0 and method.shortName|hasPrefix:"test" %} ("{{ method.shortName }}", {{type.name}}.{{ method.shortName }}), {% endif %}{% endfor %}] } {% endfor %} XCTMain([ {% for type in types.classes|based:"XCTestCase" %}{% if not type.annotations.excludeFromLinuxMain %} testCase({{ type.name }}.allTests), {% endif %}{% endfor %}]) ================================================ FILE: .github/codecov.yml ================================================ ignore: - "Tests" - "README.md" - "Documentation" - ".travis.yml" codecov: notify: require_ci_to_pass: yes coverage: precision: 1 round: up range: "70...100" status: project: yes patch: default: threshold: 0.2% changes: no parsers: gcov: branch_detection: conditional: yes loop: yes method: no macro: no comment: off ================================================ FILE: .github/jazzy.yml ================================================ module: PromiseKit custom_categories: - name: Core Components children: - Promise - Guarantee - Thenable - CatchMixin - Resolver xcodebuild_arguments: - UseModernBuildSystem=NO output: ../output # output directory is relative to config file… ugh readme: Documentation/README.md theme: fullwidth ================================================ FILE: .github/ranger.yml ================================================ merges: - action: delete_branch ================================================ FILE: .github/sourcery.yml ================================================ sources: include: - ../Tests/A+ - ../Tests/CorePromise exclude: - ../Tests/A+/0.0.0.swift - ../Tests/CorePromise/Utilities.swift templates: include: - LinuxMain.stencil output: ../Tests/LinuxMain.swift ================================================ FILE: .github/workflows/cd.yml ================================================ name: CD on: workflow_dispatch: inputs: version: required: true jobs: pods: runs-on: macos-latest steps: - name: Start Deployment uses: bobheadxi/deployments@v0.5.2 id: deployment with: step: start token: ${{ secrets.GITHUB_TOKEN }} env: pods - uses: actions/checkout@v3 with: submodules: true - run: pod trunk push --allow-warnings --skip-tests --skip-import-validation env: COCOAPODS_TRUNK_TOKEN: ${{ secrets.COCOAPODS_TRUNK_TOKEN }} - name: Seal Deployment uses: bobheadxi/deployments@v0.5.2 if: always() with: step: finish token: ${{ secrets.GITHUB_TOKEN }} status: ${{ job.status }} deployment_id: ${{ steps.deployment.outputs.deployment_id }} # carthage: # runs-on: macos-latest # steps: # - name: Start Deployment # uses: bobheadxi/deployments@v0.5.2 # id: deployment # with: # step: start # token: ${{ secrets.GITHUB_TOKEN }} # env: carthage # - uses: maxim-lobanov/setup-xcode@v1 # with: # xcode-version: ^11 # # Waiting on https://github.com/Carthage/Carthage/issues/3103 for Xcode 12 # - uses: joutvhu/get-release@v1 # id: release # with: # tag_name: ${{ github.event.inputs.version }} # env: # GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # - uses: actions/checkout@v2 # - run: carthage build --no-skip-current --platform macOS,iOS,watchOS,tvOS --archive # - run: mv PromiseKit.framework.zip PromiseKit-$v.framework.zip # - uses: actions/upload-release-asset@v1 # with: # upload_url: ${{ steps.release.outputs.upload_url }} # asset_path: ./PromiseKit-${{ github.event.inputs.version }}.framework.zip # asset_name: PromiseKit-${{ github.event.inputs.version }}.framework.zip # asset_content_type: application/zip # env: # GITHUB_TOKEN: ${{ github.token }} # - name: Seal Deployment # uses: bobheadxi/deployments@v0.5.2 # if: always() # with: # step: finish # token: ${{ secrets.GITHUB_TOKEN }} # status: ${{ job.status }} # deployment_id: ${{ steps.deployment.outputs.deployment_id }} docs: runs-on: macos-latest steps: - name: Start Deployment uses: bobheadxi/deployments@v0.5.2 id: deployment with: step: start token: ${{ secrets.GITHUB_TOKEN }} env: docs - uses: actions/checkout@v2 - run: gem install jazzy - run: | jazzy --config .github/jazzy.yml \ --github_url 'https://github.com/mxcl/PromiseKit' \ --module-version ${{ github.event.inputs.version }} - run: git remote update - run: git checkout gh-pages - run: rm -rf reference/v6 - run: mv output reference/v6 - run: git add reference/v6 - run: git config user.name github-actions - run: git config user.email github-actions@github.com - run: git commit -m 'Updated docs for v${{ github.event.inputs.version }}' - run: git remote add secure-origin https://${{ secrets.JAZZY_PAT }}@github.com/mxcl/PromiseKit.git - run: git push secure-origin gh-pages - name: Seal Deployment uses: bobheadxi/deployments@v0.5.2 if: always() with: step: finish token: ${{ secrets.GITHUB_TOKEN }} status: ${{ job.status }} deployment_id: ${{ steps.deployment.outputs.deployment_id }} ================================================ FILE: .github/workflows/ci-podspec.yml ================================================ on: workflow_dispatch: pull_request: paths: - PromiseKit.podspec jobs: lint: runs-on: macos-15 steps: - uses: maxim-lobanov/setup-xcode@v1 with: xcode-version: 16 - uses: maxim-lobanov/setup-cocoapods@v1 with: version: 1.16.2 - uses: actions/checkout@v2 with: submodules: true - run: pod lib lint --fail-fast --allow-warnings ================================================ FILE: .github/workflows/ci.yml ================================================ name: CI on: workflow_dispatch: workflow_call: pull_request: paths: - Sources/** - Tests/** - .github/workflows/ci.yml - PromiseKit.xcodeproj/** concurrency: group: ${{ github.ref }} cancel-in-progress: true jobs: linux-build: name: Linux (Swift ${{ matrix.swift }}) runs-on: ubuntu-22.04 strategy: matrix: swift: - '4.0' - '4.1' - '4.2' container: image: swift:${{ matrix.swift }} steps: - uses: actions/checkout@v1 # DO NOT UPDATE ∵ failure on older containers due to old glibc - run: swift build -Xswiftc -warnings-as-errors -Xswiftc -swift-version -Xswiftc 3 - run: swift build # can’t test ∵ generated linuxmain requires Swift 5 linux-test: name: Linux (Swift ${{ matrix.swift }}) runs-on: ubuntu-latest continue-on-error: true strategy: matrix: swift: - '5.0' - '5.1' - '5.2' - '5.3' - '5.4' - '5.5' - '5.6' - '5.7' - '5.8' - '5.9' - '5.10' - '6.0' container: image: swift:${{ matrix.swift }} steps: - uses: actions/checkout@v1 # DO NOT UPDATE ∵ failure on older containers due to old glibc - run: swift build -Xswiftc -warnings-as-errors -Xswiftc -swift-version -Xswiftc 4 if: ${{ matrix.swift < 6 }} - run: swift build -Xswiftc -warnings-as-errors -Xswiftc -swift-version -Xswiftc 4.2 if: ${{ matrix.swift < 6 }} - run: swift test --enable-code-coverage --parallel - name: Generate Coverage Report if: ${{ matrix.swift >= 6 }} run: | apt-get -qq update apt-get -qq install llvm-18 curl export b=$(swift build --show-bin-path) && llvm-cov-18 \ export -format lcov \ -instr-profile=$b/codecov/default.profdata \ --ignore-filename-regex='\.build/' \ $b/*.xctest \ > info.lcov - uses: codecov/codecov-action@v1 with: file: ./info.lcov if: ${{ matrix.swift >= 6 }} test: runs-on: macos-latest name: ${{ matrix.platform }} continue-on-error: true strategy: matrix: platform: - macOS - watchOS - tvOS - iOS # - mac-catalyst # - visionOS # ^^ both are unavailable in the github-hosted runners steps: - uses: actions/checkout@v4 - uses: mxcl/xcodebuild@v3 with: platform: ${{ matrix.platform }} code-coverage: true - uses: codecov/codecov-action@v1 test-android: name: Android runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: skiptools/swift-android-action@v2 ================================================ FILE: .github/workflows/publish.yml ================================================ name: Publish on: workflow_dispatch: inputs: version: description: semantic version to publish required: true concurrency: group: publish-{{github.event.inputs.version}} cancel-in-progress: true jobs: ci: uses: ./.github/workflows/ci.yml lint: runs-on: macos-latest strategy: matrix: xcode: - ^16 steps: - uses: maxim-lobanov/setup-xcode@v1 with: xcode-version: ${{ matrix.xcode }} - uses: actions/checkout@v3 with: submodules: true - run: pod lib lint --fail-fast --allow-warnings create-release: runs-on: ubuntu-latest needs: [ci, lint] env: v: ${{ github.event.inputs.version }} steps: - uses: actions/checkout@v3 with: fetch-depth: 0 # zero means “all” (or push fails) - name: Update committed versions run: | ruby -i -pe "sub(/CURRENT_PROJECT_VERSION = [0-9.]+/, 'CURRENT_PROJECT_VERSION = $v')" PromiseKit.xcodeproj/project.pbxproj ruby -i -pe "sub(/s.version = '[0-9.]+'/, 's.version = \'$v\'')" PromiseKit.podspec - run: | ! (git diff --quiet) - name: Commit run: | git config user.name github-actions git config user.email github-actions@github.com git commit -am "PromiseKit $v" git push - uses: softprops/action-gh-release@v1 env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} with: tag_name: ${{ github.event.inputs.version }} name: ${{ github.event.inputs.version }} cd: needs: create-release runs-on: ubuntu-latest steps: - uses: aurelien-baudet/workflow-dispatch@v2 with: workflow: CD token: ${{ secrets.JAZZY_PAT }} inputs: "{\"version\": \"${{ github.event.inputs.version }}\"}" ref: ${{ env.GITHUB_REF_NAME }} # or uses the SHA rather than branch and thus the above commit is not used wait-for-completion: true ================================================ FILE: .gitignore ================================================ *.xcodeproj/**/xcuserdata/ *.xcscmblueprint /Carthage /.build .DS_Store DerivedData /Extensions/Carthage /Tests/JS-A+/build .swiftpm/ ================================================ FILE: .gitmodules ================================================ [submodule "Extensions/Foundation"] path = Extensions/Foundation url = https://github.com/PromiseKit/Foundation.git [submodule "Extensions/UIKit"] path = Extensions/UIKit url = https://github.com/PromiseKit/UIKit.git [submodule "Extensions/Accounts"] path = Extensions/Accounts url = https://github.com/PromiseKit/Accounts.git [submodule "Extensions/MessagesUI"] path = Extensions/MessagesUI url = https://github.com/PromiseKit/MessagesUI.git [submodule "Extensions/WatchConnectivity"] path = Extensions/WatchConnectivity url = https://github.com/PromiseKit/WatchConnectivity.git [submodule "Extensions/Photos"] path = Extensions/Photos url = https://github.com/PromiseKit/Photos.git [submodule "Extensions/MapKit"] path = Extensions/MapKit url = https://github.com/PromiseKit/MapKit.git [submodule "Extensions/CloudKit"] path = Extensions/CloudKit url = https://github.com/PromiseKit/CloudKit.git [submodule "Extensions/AddressBook"] path = Extensions/AddressBook url = https://github.com/PromiseKit/AddressBook.git [submodule "Extensions/AssetsLibrary"] path = Extensions/AssetsLibrary url = https://github.com/PromiseKit/AssetsLibrary.git [submodule "Extensions/CoreLocation"] path = Extensions/CoreLocation url = https://github.com/PromiseKit/CoreLocation.git [submodule "Extensions/QuartzCore"] path = Extensions/QuartzCore url = https://github.com/PromiseKit/QuartzCore.git [submodule "Extensions/Social"] path = Extensions/Social url = https://github.com/PromiseKit/Social.git [submodule "Extensions/StoreKit"] path = Extensions/StoreKit url = https://github.com/PromiseKit/StoreKit.git [submodule "Extensions/Bolts"] path = Extensions/Bolts url = https://github.com/PromiseKit/Bolts.git [submodule "Extensions/CoreBluetooth"] path = Extensions/CoreBluetooth url = https://github.com/PromiseKit/CoreBluetooth.git [submodule "Extensions/EventKit"] path = Extensions/EventKit url = https://github.com/PromiseKit/EventKit.git [submodule "Extensions/SystemConfiguration"] path = Extensions/SystemConfiguration url = https://github.com/PromiseKit/SystemConfiguration [submodule "Extensions/Alamofire"] path = Extensions/Alamofire url = https://github.com/PromiseKit/Alamofire [submodule "Extensions/OMGHTTPURLRQ"] path = Extensions/OMGHTTPURLRQ url = https://github.com/PromiseKit/OMGHTTPURLRQ [submodule "Extensions/AVFoundation"] path = Extensions/AVFoundation url = https://github.com/PromiseKit/AVFoundation [submodule "Extensions/HomeKit"] path = Extensions/HomeKit url = https://github.com/PromiseKit/HomeKit.git [submodule "Extensions/HealthKit"] path = Extensions/HealthKit url = https://github.com/PromiseKit/PMKHealthKit ================================================ FILE: .tidelift.yml ================================================ extra_ignore_directories: [ Tests ] ================================================ FILE: .travis.yml ================================================ os: osx language: swift osx_image: xcode9.4 if: tag =~ /^[0-9]+\.[0-9]+\.[0-9]+/ stages: - swiftpm - carthage jobs: include: - &swiftpm stage: swiftpm osx_image: xcode9.4 script: swift build - <<: *swiftpm osx_image: xcode10.3 - <<: *swiftpm osx_image: xcode11.6 - &carthage stage: carthage osx_image: xcode9.4 install: sed -i '' "s/SWIFT_TREAT_WARNINGS_AS_ERRORS = NO;/SWIFT_TREAT_WARNINGS_AS_ERRORS = YES;/" *.xcodeproj/project.pbxproj script: carthage build --no-skip-current - <<: *carthage osx_image: xcode10.3 - <<: *carthage osx_image: xcode11.6 ================================================ FILE: Documentation/Appendix.md ================================================ # Common Misusage ## Doubling up Promises Don’t do this: ```swift func toggleNetworkSpinnerWithPromise(funcToCall: () -> Promise) -> Promise { return Promise { seal in firstly { setNetworkActivityIndicatorVisible(true) return funcToCall() }.then { result in seal.fulfill(result) }.always { setNetworkActivityIndicatorVisible(false) }.catch { err in seal.reject(err) } } } ``` Do this: ```swift func toggleNetworkSpinnerWithPromise(funcToCall: () -> Promise) -> Promise { return firstly { setNetworkActivityIndicatorVisible(true) return funcToCall() }.always { setNetworkActivityIndicatorVisible(false) } } ``` You already *had* a promise, you don’t need to wrap it in another promise. ## Optionals in Promises When we see `Promise`, it usually implies a misuse of promises. For example: ```swift return firstly { getItems() }.then { items -> Promise<[Item]?> in guard !items.isEmpty else { return .value(nil) } return Promise(value: items) } ``` The second `then` chooses to return `nil` in some circumstances. This choice imposes the need to check for `nil` on the consumer of the promise. It's usually better to shunt these sorts of exceptions away from the happy path and onto the error path. In this case, we can create a specific error type for this condition: ```swift return firstly { getItems() }.map { items -> [Item]> in guard !items.isEmpty else { throw MyError.emptyItems } return items } ``` > *Note*: Use `compactMap` when an API outside your control returns an Optional and you want to generate an error instead of propagating `nil`. # Tips n’ Tricks ## Background-Loaded Member Variables ```swift class MyViewController: UIViewController { private let ambience: Promise = DispatchQueue.global().async(.promise) { guard let asset = NSDataAsset(name: "CreepyPad") else { throw PMKError.badInput } let player = try AVAudioPlayer(data: asset.data) player.prepareToPlay() return player } } ``` ## Chaining Animations ```swift firstly { UIView.animate(.promise, duration: 0.3) { self.button1.alpha = 0 } }.then { UIView.animate(.promise, duration: 0.3) { self.button2.alpha = 1 } }.then { UIView.animate(.promise, duration: 0.3) { adjustConstraints() self.view.layoutIfNeeded() } } ``` ## Voiding Promises It is often convenient to erase the type of a promise to facilitate chaining. For example, `UIView.animate(.promise)` returns `Guarantee` because UIKit’s completion API supplies a `Bool`. However, we usually don’t need this value and can chain more simply if it is discarded (that is, converted to `Void`). We can use `asVoid()` to achieve this conversion: ```swift UIView.animate(.promise, duration: 0.3) { self.button1.alpha = 0 }.asVoid().done(self.nextStep) ``` For situations in which we are combining many promises into a `when`, `asVoid()` becomes essential: ```swift let p1 = foo() let p2 = bar() let p3 = baz() //… let p10 = fluff() when(fulfilled: p1.asVoid(), p2.asVoid(), /*…*/, p10.asVoid()).then { let value1 = p1.value! // safe bang since all the promises fulfilled // … let value10 = p10.value! }.catch { //… } ``` You normally don't have to do this explicitly because `when` does it for you for up to 5 parameters. ## Blocking (Await) Sometimes you have to block the main thread to await completion of an asynchronous task. In these cases, you can (with caution) use `wait`: ```swift public extension UNUserNotificationCenter { var wasPushRequested: Bool { let settings = Guarantee(resolver: getNotificationSettings).wait() return settings != .notDetermined } } ``` The task under the promise **must not** call back onto the current thread or it will deadlock. ## Starting a Chain on a Background Queue/Thread `firstly` deliberately does not take a queue. A detailed rationale for this choice can be found in the ticket tracker. So, if you want to start a chain by dispatching to the background, you have to use `DispatchQueue.async`: ```swift DispatchQueue.global().async(.promise) { return value }.done { value in //… } ``` However, this function cannot return a promise because of Swift compiler ambiguity issues. Thus, if you must start a promise on a background queue, you need to do something like this: ```swift Promise { seal in DispatchQueue.global().async { seal(value) } }.done { value in //… } ``` Or more simply (though with caveats; see the documentation for `wait`): ```swift DispatchQueue.global().async(.promise) { return try fetch().wait() }.done { value in //… } ``` However, you shouldn't need to do this often. If you find yourself wanting to use this technique, perhaps you should instead modify the code for `fetch` to make it do its work on a background thread. Promises abstract asynchronicity, so exploit and support that model. Design your APIs so that consumers don’t have to care what queue your functions run on. ================================================ FILE: Documentation/CommonPatterns.md ================================================ # Common Patterns One feature of promises that makes them particularly useful is that they are composable. This fact enables complex, yet safe asynchronous patterns that would otherwise be quite intimidating when implemented with traditional methods. ## Chaining The most common pattern is chaining: ```swift firstly { fetch() }.then { map($0) }.then { set($0) return animate() }.ensure { // something that should happen whatever the outcome }.catch { handle(error: $0) } ``` If you return a promise in a `then`, the next `then` *waits* on that promise before continuing. This is the essence of promises. Promises are easy to compose, so they encourage you to develop highly asynchronous apps without fear of the spaghetti code (and associated refactoring pains) of asynchronous systems that use completion handlers. ## APIs That Use Promises Promises are composable, so return them instead of accepting completion blocks: ```swift class MyRestAPI { func user() -> Promise { return firstly { URLSession.shared.dataTask(.promise, with: url) }.compactMap { try JSONSerialization.jsonObject(with: $0.data) as? [String: Any] }.map { dict in User(dict: dict) } } func avatar() -> Promise { return user().then { user in URLSession.shared.dataTask(.promise, with: user.imageUrl) }.compactMap { UIImage(data: $0.data) } } } ``` This way, asynchronous chains can cleanly and seamlessly incorporate code from all over your app without violating architectural boundaries. > *Note*: We provide [promises for Alamofire](https://github.com/PromiseKit/Alamofire-) too! ## Background Work ```swift class MyRestAPI { func avatar() -> Promise { let bgq = DispatchQueue.global(qos: .userInitiated) return firstly { user() }.then(on: bgq) { user in URLSession.shared.dataTask(.promise, with: user.imageUrl) }.compactMap(on: bgq) { UIImage(data: $0) } } } ``` All PromiseKit handlers take an `on` parameter that lets you designate the dispatch queue on which to run the handler. The default is always the main queue. PromiseKit is *entirely* thread safe. > *Tip*: With caution, you can have all `then`, `map`, `compactMap`, etc., run on a background queue. See `PromiseKit.conf`. Note that we suggest only changing the queue for the `map` suite of functions, so `done` and `catch` will continue to run on the main queue, which is *usually* what you want. ## Failing Chains If an error occurs mid-chain, simply throw an error: ```swift firstly { foo() }.then { baz in bar(baz) }.then { result in guard !result.isBad else { throw MyError.myIssue } //… return doOtherThing() } ``` The error will surface at the next `catch` handler. Since promises handle thrown errors, you don't have to wrap calls to throwing functions in a `do` block unless you really want to handle the errors locally: ```swift foo().then { baz in bar(baz) }.then { result in try doOtherThing() }.catch { error in // if doOtherThing() throws, we end up here } ``` > *Tip*: Swift lets you define an inline `enum Error` inside the function you are working on. This isn’t *great* coding practice, but it's better than avoiding throwing an error because you couldn't be bothered to define a good global `Error` `enum`. ## Abstracting Away Asynchronicity ```swift var fetch = API.fetch() override func viewDidAppear() { fetch.then { items in //… } } func buttonPressed() { fetch.then { items in //… } } func refresh() -> Promise { // ensure only one fetch operation happens at a time if fetch.isResolved { startSpinner() fetch = API.fetch().ensure { stopSpinner() } } return fetch } ``` With promises, you don’t need to worry about *when* your asynchronous operation finishes. Just act like it already has. Above, we see that you can call `then` as many times on a promise as you like. All the blocks will be executed in the order they were added. ## Chaining Sequences When you have a series of tasks to perform on an array of data: ```swift // fade all visible table cells one by one in a “cascading” effect var fade = Guarantee() for cell in tableView.visibleCells { fade = fade.then { UIView.animate(.promise, duration: 0.1) { cell.alpha = 0 } } } fade.done { // finish } ``` Or if you have an array of closures that return promises: ```swift var foo = Promise() for nextPromise in arrayOfClosuresThatReturnPromises { foo = foo.then(nextPromise) // ^^ you rarely would want an array of promises instead, since then // they have all already started, you may as well use `when()` } foo.done { // finish } ``` > *Note*: You *usually* want `when()`, since `when` executes all of its component promises in parallel and so completes much faster. Use the pattern shown above in situations where tasks *must* be run sequentially; animation is a good example. > We also provide `when(concurrently:)`, which lets you schedule more than one promise at a time if you need to. ## Timeout ```swift let fetches: [Promise] = makeFetches() let timeout = after(seconds: 4) race(when(fulfilled: fetches).asVoid(), timeout).then { //… } ``` `race` continues as soon as one of the promises it is watching finishes. Make sure the promises you pass to `race` are all of the same type. The easiest way to ensure this is to use `asVoid()`. Note that if any component promise rejects, the `race` will reject, too. # Minimum Duration Sometimes you need a task to take *at least* a certain amount of time. (For example, you want to show a progress spinner, but if it shows for less than 0.3 seconds, the UI appears broken to the user.) ```swift let waitAtLeast = after(seconds: 0.3) firstly { foo() }.then { waitAtLeast }.done { //… } ``` The code above works because we create the delay *before* we do work in `foo()`. By the time we get to waiting on that promise, either it will have already timed out or we will wait for whatever remains of the 0.3 seconds before continuing the chain. ## Cancellation Promises don’t have a `cancel` function, but they do support cancellation through a special error type that conforms to the `CancellableError` protocol. ```swift func foo() -> (Promise, cancel: () -> Void) { let task = Task(…) var cancelme = false let promise = Promise { seal in task.completion = { value in guard !cancelme else { return reject(PMKError.cancelled) } seal.fulfill(value) } task.start() } let cancel = { cancelme = true task.cancel() } return (promise, cancel) } ``` Promises don’t have a `cancel` function because you don’t want code outside of your control to be able to cancel your operations--*unless*, of course, you explicitly want to enable that behavior. In cases where you do want cancellation, the exact way that it should work will vary depending on how the underlying task supports cancellation. PromiseKit provides cancellation primitives but no concrete API. **Important**: Errors which conform to the `CancellableError` protocol do *not* normally trigger the `.catch` block. Cancelation is neither success nor failure, so cancelled chains do not call `catch` handlers by default. However you can intercept cancellation if you like: ```swift foo.then { //… }.catch(policy: .allErrors) { // cancelled errors are handled *as well* } ``` **Important**: Canceling a promise chain is *not* the same as canceling the underlying asynchronous task. Promises are wrappers around asynchronicity, but they have no control over the underlying tasks. If you need to cancel an underlying task, you need to cancel the underlying task! > The library [CancellablePromiseKit](https://github.com/johannesd/CancellablePromiseKit) extends the concept of Promises to fully cover cancellable tasks. ## Retry / Polling ```swift func attempt(maximumRetryCount: Int = 3, delayBeforeRetry: DispatchTimeInterval = .seconds(2), _ body: @escaping () -> Promise) -> Promise { var attempts = 0 func attempt() -> Promise { attempts += 1 return body().recover { error -> Promise in guard attempts < maximumRetryCount else { throw error } return after(delayBeforeRetry).then(attempt) } } return attempt() } attempt(maximumRetryCount: 3) { flakeyTask(parameters: foo) }.then { //… }.catch { _ in // we attempted three times but still failed } ``` In most cases, you should probably supplement the code above so that it re-attempts only for specific error conditions. ## Wrapping Delegate Systems Be careful with Promises and delegate systems, as they are not always compatible. Promises complete *once*, whereas most delegate systems may notify their delegate many times. This is why, for example, there is no PromiseKit extension for a `UIButton`. A good example of an appropriate time to wrap delegation is when you need a single `CLLocation` lookup: ```swift extension CLLocationManager { static func promise() -> Promise { return PMKCLLocationManagerProxy().promise } } class PMKCLLocationManagerProxy: NSObject, CLLocationManagerDelegate { private let (promise, seal) = Promise<[CLLocation]>.pending() private var retainCycle: PMKCLLocationManagerProxy? private let manager = CLLocationManager() init() { super.init() retainCycle = self manager.delegate = self // does not retain hence the `retainCycle` property promise.ensure { // ensure we break the retain cycle self.retainCycle = nil } } @objc fileprivate func locationManager(_: CLLocationManager, didUpdateLocations locations: [CLLocation]) { seal.fulfill(locations) } @objc func locationManager(_: CLLocationManager, didFailWithError error: Error) { seal.reject(error) } } // use: CLLocationManager.promise().then { locations in //… }.catch { error in //… } ``` > Please note: we provide this promise with our CoreLocation extensions at > https://github.com/PromiseKit/CoreLocation ## Recovery Sometimes you don’t want an error to cascade. Instead, you want to supply a default result: ```swift CLLocationManager.requestLocation().recover { error -> Promise in guard error == MyError.airplaneMode else { throw error } return .value(CLLocation.savannah) }.done { location in //… } ``` Be careful not to ignore all errors, though! Recover only those errors that make sense to recover. ## Promises for Modal View Controllers ```swift class ViewController: UIViewController { private let (promise, seal) = Guarantee<…>.pending() // use Promise if your flow can fail func show(in: UIViewController) -> Promise<…> { in.show(self, sender: in) return promise } func done() { dismiss(animated: true) seal.fulfill(…) } } // use: ViewController().show(in: self).done { //… }.catch { error in //… } ``` This is the best approach we have found, which is a pity as it requires the presentee to control the presentation and requires the presentee to dismiss itself explicitly. Nothing seems to beat storyboard segues for decoupling an app's controllers. ## Saving Previous Results Let’s say you have: ```swift login().then { username in fetch(avatar: username) }.done { image in //… } ``` What if you want access to both `username` and `image` in your `done`? The most obvious way is to use nesting: ```swift login().then { username in fetch(avatar: username).done { image in // we have access to both `image` and `username` } }.done { // the chain still continues as you'd expect } ``` However, such nesting reduces the clarity of the chain. Instead, we could use Swift tuples: ```swift login().then { username in fetch(avatar: username).map { ($0, username) } }.then { image, username in //… } ``` The code above simply maps `Promise` into `Promise<(UIImage, String)>`. ## Waiting on Multiple Promises, Whatever Their Result Use `when(resolved:)`: ```swift when(resolved: a, b).done { (results: [Result]) in // `Result` is an enum of `.fulfilled` or `.rejected` } // ^^ cannot call `catch` as `when(resolved:)` returns a `Guarantee` ``` Generally, you don't want this! People ask for it a lot, but usually because they are trying to ignore errors. What they really need is to use `recover` on one of the promises. Errors happen, so they should be handled; you usually don't want to ignore them. ================================================ FILE: Documentation/Examples/ImageCache.md ================================================ # Image Cache with Promises Here is an example of a simple image cache that uses promises to simplify the state machine: ```swift import Foundation import PromiseKit /** * Small (10 images) * Thread-safe * Consolidates multiple requests to the same URLs * Removes stale entries (FIXME well, strictly we may delete while fetching from cache, but this is unlikely and non-fatal) * Completely _ignores_ server caching headers! */ private let q = DispatchQueue(label: "org.promisekit.cache.image", attributes: .concurrent) private var active: [URL: Promise] = [:] private var cleanup = Promise() public func fetch(image url: URL) -> Promise { var promise: Promise? q.sync { promise = active[url] } if let promise = promise { return promise } q.sync { promise = Promise(.start) { let dst = try url.cacheDestination() guard !FileManager.default.isReadableFile(atPath: dst.path) else { return Promise(dst) } return Promise { seal in URLSession.shared.downloadTask(with: url) { tmpurl, _, error in do { guard let tmpurl = tmpurl else { throw error ?? E.unexpectedError } try FileManager.default.moveItem(at: tmpurl, to: dst) seal.fulfill(dst) } catch { seal.reject(error) } }.resume() } }.then(on: .global(QoS: .userInitiated)) { try Data(contentsOf: $0) } active[url] = promise if cleanup.isFulfilled { cleanup = promise!.asVoid().then(on: .global(QoS: .utility), execute: docleanup) } } return promise! } public func cached(image url: URL) -> Data? { guard let dst = try? url.cacheDestination() else { return nil } return try? Data(contentsOf: dst) } public func cache(destination remoteUrl: URL) throws -> URL { return try remoteUrl.cacheDestination() } private func cache() throws -> URL { guard let dst = FileManager.default.docs? .appendingPathComponent("Library") .appendingPathComponent("Caches") .appendingPathComponent("cache.img") else { throw E.unexpectedError } try FileManager.default.createDirectory(at: dst, withIntermediateDirectories: true, attributes: [:]) return dst } private extension URL { func cacheDestination() throws -> URL { var fn = String(hashValue) let ext = pathExtension // many of Apple's functions don’t recognize file type // unless we preserve the file extension if !ext.isEmpty { fn += ".\(ext)" } return try cache().appendingPathComponent(fn) } } enum E: Error { case unexpectedError case noCreationTime } private func docleanup() throws { var contents = try FileManager.default .contentsOfDirectory(at: try cache(), includingPropertiesForKeys: [.creationDateKey]) .map { url -> (Date, URL) in guard let date = try url.resourceValues(forKeys: [.creationDateKey]).creationDate else { throw E.noCreationTime } return (date, url) }.sorted(by: { $0.0 > $1.0 }) while contents.count > 10 { let rm = contents.popLast()!.1 try FileManager.default.removeItem(at: rm) } } ```` ================================================ FILE: Documentation/Examples/URLSession+BadResponseErrors.swift ================================================ Promise(.pending) { seal in URLSession.shared.dataTask(with: rq, completionHandler: { data, rsp, error in if let data = data { seal.fulfill(data) } else if let error = error { if case URLError.badServerResponse = error, let rsp = rsp as? HTTPURLResponse { seal.reject(Error.badResponse(rsp.statusCode)) } else { seal.reject(error) } } else { seal.reject(PMKError.invalidCallingConvention) } }) } enum Error: Swift.Error { case badUrl case badResponse(Int) } ================================================ FILE: Documentation/Examples/detweet.swift ================================================ #!/usr/bin/swift sh import Foundation import PromiseKit // @mxcl ~> 6.5 import Swifter // @mattdonnelly == b27a89 let swifter = Swifter( consumerKey: "FILL", consumerSecret: "ME", oauthToken: "IN", oauthTokenSecret: "https://developer.twitter.com/en/docs/basics/apps/overview.html" ) extension JSON { var date: Date? { guard let string = string else { return nil } let formatter = DateFormatter() formatter.dateFormat = "EEE MMM dd HH:mm:ss Z yyyy" return formatter.date(from: string) } } let twoMonthsAgo = Date() - 24*60*60*30*2 print("Deleting qualifying tweets before:", twoMonthsAgo) func deleteTweets(maxID: String? = nil) -> Promise { return Promise { seal in swifter.getTimeline(for: "mxcl", count: 200, maxID: maxID, success: { json in if json.array!.count <= 1 { // if we get one result for a requested maxID, we're done return seal.fulfill() } for item in json.array! { let date = item["created_at"].date! guard date < twoMonthsAgo, item["favorite_count"].integer! < 2 else { continue } swifter.destroyTweet(forID: id, success: { _ in print("D:", item["text"].string!) }, failure: seal.reject) } let next = json.array!.last!["id_str"].string! deleteTweets(maxID: next).pipe(to: seal.resolve) }, failure: seal.reject) } } func deleteFavorites(maxID: String? = nil) -> Promise { return Promise { seal in swifter.getRecentlyFavoritedTweets(count: 200, maxID: maxID, success: { json in if json.array!.count <= 1 { return seal.fulfill() } for item in json.array! { guard item["created_at"].date! < twoMonthsAgo else { continue } swifter.unfavoriteTweet(forID: item["id_str"].string!, success: { _ in print("D❤️:", item["text"].string!) }, failure: seal.reject) } let next = json.array!.last!["id_str"].string! deleteFavorites(maxID: next).pipe(to: seal.resolve) }, failure: seal.reject) } } func unblockPeople(cursor: String? = nil) -> Promise { return Promise { seal in swifter.getBlockedUsersIDs(stringifyIDs: "true", cursor: cursor, success: { json, prev, next in for id in json.array! { print("Unblocking:", id) swifter.unblockUser(for: .id(id.string!)) } if let next = next, !next.isEmpty, next != prev, next != "0" { unblockPeople(cursor: next).pipe(to: seal.resolve) } else { seal.fulfill() } }, failure: seal.reject) } } firstly { when(fulfilled: deleteTweets(), deleteFavorites(), unblockPeople()) }.done { exit(0) }.catch { print("error:", $0) exit(1) } RunLoop.main.run() ================================================ FILE: Documentation/FAQ.md ================================================ # FAQ ## Why should I use PromiseKit over X-Promises-Foo? * PromiseKit has a heavy focus on **developer experience**. You’re a developer; do you care about your experience? Yes? Then pick PromiseKit. * Do you care about having any bugs you find fixed? Then pick PromiseKit. * Do you care about having your input heard and reacted to in a fast fashion? Then pick PromiseKit. * Do you want a library that has been maintained continuously and passionately for 6 years? Then pick PromiseKit. * Do you want a library that the community has chosen to be their №1 Promises/Futures library? Then pick PromiseKit. * Do you want to be able to use Promises with Apple’s SDKs rather than having to do all the work of writing the Promise implementations yourself? Then pick PromiseKit. * Do you want to be able to use Promises with Swift 3.x, Swift 4.x, ObjC, iOS, tvOS, watchOS, macOS, Android & Linux? Then pick PromiseKit. * PromiseKit verifies its correctness by testing against the entire [Promises/A+ test suite](https://github.com/promises-aplus/promises-tests). ## How do I create a fulfilled `Void` promise? ```swift let foo = Promise() // or: let bar = Promise.value(()) ``` ## How do I “early `return`”? ```swift func foo() -> Promise { guard thingy else { return Promise() } //… } func bar() -> Promise { guard thingy else { return .value(instanceOfSomethingNotVoid) } //… } ``` ## Do I need to worry about retain cycles? Generally, no. Once a promise completes, all handlers are released and so any references to `self` are also released. However, if your chain contains side effects that you would typically not want to happen after, say, a view controller is popped, then you should still use `weak self` (and check for `self == nil`) to prevent any such side effects. *However*, in our experience most things that developers consider side effects that should be protected against are in fact *not* side effects. Side effects include changes to global application state. They *do not* include changing the display state of a view-controller. So, protect against setting `UserDefaults` or modifying the application database, and don't bother protecting against changing the text in a `UILabel`. [This StackOverflow question](https://stackoverflow.com/questions/39281214/should-i-use-weak-self-in-promisekit-blocks) has some good discussion on this topic. ## Do I need to retain my promises? No. Every promise handler retains its promise until the handler is executed. Once all handlers have been executed, the promise is deallocated. So you only need to retain the promise if you need to refer to its final value after its chain has completed. ## Where should I put my `catch`? `catch` deliberately terminates the chain. You should put it low in your promise hierarchy at a point as close to the root as possible. Typically, this would be somewhere such as a view controller, where your `catch` can then display a message to the user. This means you should be writing one catch for many `then`s and returning promises that do not have internal `catch` handlers of their own. This is obviously a guideline; do what is necessary. ## How do branched chains work? Suppose you have a promise: ``` let promise = foo() ``` And you call `then` twice: ``` promise.then { // branch A } promise.then { // branch B } ``` You now have a branched chain. When `promise` resolves, both chains receive its value. However, the two chains are entirely separate and Swift will prompt you to ensure that both have `catch` handlers. You can most likely ignore the `catch` for one of these branches, but be careful: in these situations, Swift cannot help you ensure that your chains are error-handled. ``` promise.then { // branch A }.catch { error in //… } _ = promise.then { print("foo") // ignoring errors here as print cannot error and we handle errors above } ``` It may be safer to recombine the two branches into a single chain again: ``` let p1 = promise.then { // branch A } let p2 = promise.then { // branch B } when(fulfilled: p1, p2).catch { error in //… } ``` > It's worth noting that you can add multiple `catch` handlers to a promise, too. > And indeed, both will be called if the chain is rejected. ## Is PromiseKit “heavy”? No. PromiseKit contains hardly any source code. In fact, it is quite lightweight. Any “weight” relative to other promise implementations derives from 6 years of bug fixes and tuning, from the fact that we have *stellar* Objective-C-to-Swift bridging and from important things such as [Zalgo prevention](http://blog.izs.me/post/59142742143/designing-apis-for-asynchrony) that hobby-project implementations don’t consider. ## Why is debugging hard? Because promises always execute via dispatch, the backtrace you see at the point of an error has less information than is usually required to trace the path of execution. One solution is to turn off dispatch during debugging: ```swift // Swift DispatchQueue.default = zalgo //ObjC PMKSetDefaultDispatchQueue(zalgo) ``` Don’t leave this on. In normal use, we always dispatch to avoid you accidentally writing a common bug pattern. See [this blog post](http://blog.izs.me/post/59142742143/designing-apis-for-asynchrony). ## Where is `all()`? Some promise libraries provide `all` for awaiting multiple results. We call this function `when`, but it is the same thing. We chose `when` because it's the more common term and because we think it reads better in code. ## How can I test APIs that return promises? You need to use `XCTestExpectation`. We also define `wait()` and `hang()`. Use them if you must, but be careful because they block the current thread! ## Is PromiseKit thread-safe? Yes, entirely. However the code *you* write in your `then`s might not be! Just make sure you don’t access state outside the chain from concurrent queues. By default, PromiseKit handlers run on the `main` thread, which is serial, so you typically won't have to worry about this. ## Why are there separate classes for Objective-C and Swift? `Promise` is generic and and so cannot be represented by Objective-C. ## Does PromiseKit conform to Promises/A+? Yes. We have tests that prove this. ## How do PromiseKit and RxSwift/ReactiveSwift differ? PromiseKit is a lot simpler. The top-level difference between PromiseKit and RxSwift is that RxSwift `Observable`s (roughly analogous to PromiseKit `Promise`s) do not necessarily return a single result: they may emit zero, one, or an infinite stream of values. This small conceptual change leads to an API that's both surprisingly powerful and surprisingly complex. RxSwift requires commitment to a paradigm shift in how you program. It proposes that you restructure your code as a matrix of interacting value pipelines. When applied properly to a suitable problem, RxSwift can yield great benefits in robustness and simplicity. But not all applications are suitable for RxSwift. By contrast, PromiseKit selectively applies the best parts of reactive programming to the hardest part of pure Swift development, the management of asynchronicity. It's a broadly applicable tool. Most asynchronous code can be clarified, simplified and made more robust just by converting it to use promises. (And the conversion process is easy.) Promises make for code that is clear to most developers. RxSwift, perhaps not. Take a look at this [sign-up panel](https://github.com/ReactiveX/RxSwift/tree/master/RxExample/RxExample/Examples/GitHubSignup) implemented in RxSwift and see what you think. (Note that this is one of RxSwift's own examples.) Even where PromiseKit and RxSwift are broadly similar, there are many differences in implementation: * RxSwift has a separate API for chain-terminating elements ("subscribers") versus interior elements. In PromiseKit, all elements of a chain use roughly the same code pattern. * The RxSwift API to define an interior element of a chain (an "operator") is hair-raisingly complex. So, RxSwift tries hard to supply every operator you might ever want to use right off the shelf. There are hundreds. PromiseKit supplies a few utilities to help with specific scenarios, but because it's trivial to write your own chain elements, there's no need for all this extra code in the library. * PromiseKit dispatches the execution of every block. RxSwift dispatches only when told to do so. Moreover, the current dispatching state is an attribute of the chain, not the specific block, as it is in PromiseKit. The RxSwift system is more powerful but more complex. PromiseKit is simple, predictable and safe. * In PromiseKit, both sides of a branched chain refer back to their shared common ancestors. In RxSwift, branching normally creates a duplicate parallel chain that reruns the code at the head of the chain...except when it doesn't. The rules for determining what will actually happen are complex, and given a chain created by another chunk of code, you can't really tell what the behavior will be. * Because RxSwift chains don't necessarily terminate on their own, RxSwift needs you to take on some explicit garbage collection duties to ensure that pipelines that are no longer needed are properly deallocated. All promises yield a single value, terminate and then automatically deallocate themselves. You can find some additional discussion in [this ticket](https://github.com/mxcl/PromiseKit/issues/484). ## Why can’t I return from a catch like I can in JavaScript? Swift demands that functions have one purpose. Thus, we have two error handlers: * `catch`: ends the chain and handles errors * `recover`: attempts to recover from errors in a chain You want `recover`. ## When do promises “start”? Often people are confused about when Promises “start”. Is it immediately? Is it later? Is it when you call `then`? The answer is: The promise **body** executes during initialization of the promise, on the current thread. As an example, `"Executing the promise body"` will be printed to the console right after the promise is created, without having to call `then` on the promise. ```swift let testPromise = Promise { print("Executing the promise body.") return $0.fulfill(true) } ``` But what about asynchronous tasks that you create in your promise's body? They behave the same way as they would without using PromiseKit. Here's a simple example: ```swift let testPromise = Promise { seal in print("Executing the promise body.") DispatchQueue.main.asyncAfter(deadline: .now() + 3.0) { print("Executing asyncAfter.") return seal.fulfill(true) } } ``` The message `"Executing the promise body."` is being logged right away, but the message `"Executing asyncAfter."` is only logged three seconds later. In this case `DispatchQueue` is responsible for deciding when to execute the task you pass to it, PromiseKit has nothing to do with it. ## What is a good way to use Firebase with PromiseKit There is no good way to use Firebase with PromiseKit. See the next question for a more detailed rationale. The best option is to embed your chain in your Firebase handler: ``` foo.observe(.value) { snapshot in firstly { bar(with: snapshot) }.then { baz() }.then { baffle() }.catch { //… } } ``` ## I need my `then` to fire multiple times Then we’re afraid you cannot use PromiseKit for that event. Promises only resolve *once*. This is the fundamental nature of promises and it is considered a feature because it gives you guarantees about the flow of your chains. ## How do I change the default queues that handlers run on? You can change the values of `PromiseKit.conf.Q`. There are two variables that change the default queues that the two kinds of handler run on. A typical pattern is to change all your `then`-type handlers to run on a background queue and to have all your “finalizers” run on the main queue: ``` PromiseKit.conf.Q.map = .global() PromiseKit.conf.Q.return = .main //NOTE this is the default ``` Be very careful about setting either of these queues to `nil`. It has the effect of running *immediately*, and this is not what you usually want to do in your application. This is, however, useful when you are running specs and want your promises to resolve immediately. (This is basically the same idea as "stubbing" an HTTP request.) ```swift // in your test suite setup code PromiseKit.conf.Q.map = nil PromiseKit.conf.Q.return = nil ``` ## How do I use PromiseKit on the server side? If your server framework requires that the main queue remain unused (e.g., Kitura), then you must use PromiseKit 6 and you must tell PromiseKit not to dispatch to the main queue by default. This is easy enough: ```swift PromiseKit.conf.Q = (map: DispatchQueue.global(), return: DispatchQueue.global()) ``` > Note, we recommend using your own queue rather than `.global()`, we've seen better performance this way. Here’s a more complete example: ```swift import Foundation import HeliumLogger import Kitura import LoggerAPI import PromiseKit HeliumLogger.use(.info) let pmkQ = DispatchQueue(label: "pmkQ", qos: .default, attributes: .concurrent, autoreleaseFrequency: .workItem) PromiseKit.conf.Q = (map: pmkQ, return: pmkQ) let router = Router() router.get("/") { _, response, next in Log.info("Request received") after(seconds: 1.0).done { Log.info("Sending response") response.send("OK") next() } } Log.info("Starting server") Kitura.addHTTPServer(onPort: 8888, with: router) Kitura.run() ``` ## How do I control console output? By default PromiseKit emits console messages when certain events occur. These events include: - A promise or guarantee has blocked the main thread - A promise has been deallocated without being fulfilled - An error which occurred while fulfilling a promise was swallowed using cauterize You may turn off or redirect this output by setting a thread safe closure in [PMKConfiguration](https://github.com/mxcl/PromiseKit/blob/master/Sources/Configuration.swift) **before** processing any promises. For example, to turn off console output: ```swift conf.logHandler = { event in } ``` ## My question was not answered [Please open a ticket](https://github.com/mxcl/PromiseKit/issues/new). ================================================ FILE: Documentation/GettingStarted.md ================================================ # `then` and `done` Here is a typical promise chain: ```swift firstly { login() }.then { creds in fetch(avatar: creds.user) }.done { image in self.imageView = image } ``` If this code used completion handlers, it would look like this: ```swift login { creds, error in if let creds = creds { fetch(avatar: creds.user) { image, error in if let image = image { self.imageView = image } } } } ``` `then` *is* just another way to structure completion handlers, but it is also quite a bit more. At this initial stage of our understanding, it mostly helps readability. The promise chain above is easy to scan and understand: one asynchronous operation leads into the other, line by line. It's as close to procedural code as we can easily come given the current state of Swift. `done` is the same as `then` but you cannot return a promise. It is typically the end of the “success” part of the chain. Above, you can see that we receive the final image in our `done` and use it to set up the UI. Let’s compare the signatures of the two login methods: ```swift func login() -> Promise // Compared with: func login(completion: (Creds?, Error?) -> Void) // ^^ ugh. Optionals. Double optionals. ``` The distinction is that with promises, your functions return *promises* instead of accepting and running callbacks. Each handler in a chain returns a promise. `Promise` objects define the `then` method, which waits for the completion of the promise before continuing the chain. Chains resolve procedurally, one promise at a time. A `Promise` represents the future value of an asynchronous task. It has a type that represents the type of object it wraps. For example, in the example above, `login` is a function that returns a `Promise` that *will* represent an instance of `Creds`. > *Note*: `done` is new to PromiseKit 5. We previously defined a variant of `then` that did not require you to return a promise. Unfortunately, this convention often confused Swift and led to odd and hard-to-debug error messages. It also made using PromiseKit more painful. The introduction of `done` lets you type out promise chains that compile without additional qualification to help the compiler figure out type information. --- You may notice that unlike the completion pattern, the promise chain appears to ignore errors. This is not the case! In fact, it has the opposite effect: the promise chain makes error handling more accessible and makes errors harder to ignore. # `catch` With promises, errors cascade along the promise chain, ensuring that your apps are robust and your code is clear: ```swift firstly { login() }.then { creds in fetch(avatar: creds.user) }.done { image in self.imageView = image }.catch { // any errors in the whole chain land here } ``` > Swift emits a warning if you forget to `catch` a chain. But we'll > talk about that in more detail later. Each promise is an object that represents an individual, asynchronous task. If a task fails, its promise becomes *rejected*. Chains that contain rejected promises skip all subsequent `then`s. Instead, the next `catch` is executed. (Strictly speaking, *all* subsequent `catch` handlers are executed.) For fun, let’s compare this pattern with its completion handler equivalent: ```swift func handle(error: Error) { //… } login { creds, error in guard let creds = creds else { return handle(error: error!) } fetch(avatar: creds.user) { image, error in guard let image = image else { return handle(error: error!) } self.imageView.image = image } } ``` The use of `guard` and a consolidated error handler help, but the promise chain’s readability speaks for itself. # `ensure` We have learned to compose asynchronicity. Next let’s extend our primitives: ```swift firstly { UIApplication.shared.isNetworkActivityIndicatorVisible = true return login() }.then { fetch(avatar: $0.user) }.done { self.imageView = $0 }.ensure { UIApplication.shared.isNetworkActivityIndicatorVisible = false }.catch { //… } ``` No matter the outcome of your chain—-failure or success—-your `ensure` handler is always called. Let’s compare this pattern with its completion handler equivalent: ```swift UIApplication.shared.isNetworkActivityIndicatorVisible = true func handle(error: Error) { UIApplication.shared.isNetworkActivityIndicatorVisible = false //… } login { creds, error in guard let creds = creds else { return handle(error: error!) } fetch(avatar: creds.user) { image, error in guard let image = image else { return handle(error: error!) } self.imageView.image = image UIApplication.shared.isNetworkActivityIndicatorVisible = false } } ``` It would be very easy for someone to amend this code and forget to unset the activity indicator, leading to a bug. With promises, this type of error is almost impossible: the Swift compiler resists your supplementing the chain without using promises. You almost won’t need to review the pull requests. > *Note*: PromiseKit has perhaps capriciously switched between the names `always` and `ensure` for this function several times in the past. Sorry about this. We suck. You can also use `finally` as an `ensure` that terminates the promise chain and does not return a value: ``` spinner(visible: true) firstly { foo() }.done { //… }.catch { //… }.finally { self.spinner(visible: false) } ``` # `when` With completion handlers, reacting to multiple asynchronous operations is either slow or hard. Slow means doing it serially: ```swift operation1 { result1 in operation2 { result2 in finish(result1, result2) } } ``` The fast (*parallel*) path code makes the code less clear: ```swift var result1: …! var result2: …! let group = DispatchGroup() group.enter() group.enter() operation1 { result1 = $0 group.leave() } operation2 { result2 = $0 group.leave() } group.notify(queue: .main) { finish(result1, result2) } ``` Promises are easier: ```swift firstly { when(fulfilled: operation1(), operation2()) }.done { result1, result2 in //… } ``` `when` takes promises, waits for them to resolve and returns a promise containing the results. As with any promise chain, if any of the component promises fail, the chain calls the next `catch`. # PromiseKit Extensions When we made PromiseKit, we understood that we wanted to use *only* promises to implement asynchronous behavior. So wherever possible, we offer extensions to Apple’s APIs that reframe the API in terms of promises. For example: ```swift firstly { CLLocationManager.promise() }.then { location in CLGeocoder.reverseGeocode(location) }.done { placemarks in self.placemark.text = "\(placemarks.first)" } ``` To use these extensions, you need to specify subspecs: ```ruby pod "PromiseKit" pod "PromiseKit/CoreLocation" pod "PromiseKit/MapKit" ``` All of these extensions are available at the [PromiseKit organization](https://github.com/PromiseKit). Go there to see what's available and to read the source code and documentation. Every file and function has been copiously documented. > We also provide extensions for common libraries such as [Alamofire](https://github.com/PromiseKit/Alamofire-). # Making Promises The standard extensions will take you a long way, but sometimes you'll still need to start chains of your own. Maybe you're using a third party API that doesn’t provide promises, or perhaps you wrote your own asynchronous system. Either way, it's easy to add promises. If you look at the code of the standard extensions, you'll see that it uses the same approach described below. Let’s say we have the following method: ```swift func fetch(completion: (String?, Error?) -> Void) ``` How do we convert this to a promise? Well, it's easy: ```swift func fetch() -> Promise { return Promise { fetch(completion: $0.resolve) } } ``` You may find the expanded version more readable: ```swift func fetch() -> Promise { return Promise { seal in fetch { result, error in seal.resolve(result, error) } } } ``` The `seal` object that the `Promise` initializer provides to you defines many methods for handling garden-variety completion handlers. It even covers a variety of rarer situations, thus making it easy for you to add promises to an existing codebase. > *Note*: We tried to make it so that you could just do `Promise(fetch)`, but we were not able to make this simpler pattern work universally without requiring extra disambiguation for the Swift compiler. Sorry; we tried. > *Note*: In PMK 4, this initializer provided two parameters to your closure: `fulfill` and `reject`. PMK 5 and 6 give you an object that has both `fulfill` and `reject` methods, but also many variants of the method `resolve`. You can typically just pass completion handler parameters to `resolve` and let Swift figure out which variant to apply to your particular case (as shown in the example above). > *Note* `Guarantees` (below) have a slightly different initializer (since they cannot error) so the parameter to the initializer closure is just a closure. Not a `Resolver` object. Thus do `seal(value)` rather than `seal.fulfill(value)`. This is because there is no variations in what guarantees can be sealed with, they can *only* fulfill. # `Guarantee` Since PromiseKit 5, we have provided `Guarantee` as a supplementary class to `Promise`. We do this to complement Swift’s strong error handling system. Guarantees *never* fail, so they cannot be rejected. A good example is `after`: ``` firstly { after(seconds: 0.1) }.done { // there is no way to add a `catch` because after cannot fail. } ``` Swift warns you if you don’t terminate a regular `Promise` chain (i.e., not a `Guarantee` chain). You're expected to silence this warning by supplying either a `catch` or a `return`. (In the latter case, you will then have to `catch` at the point where you receive that promise.) Use `Guarantee`s wherever possible so that your code has error handling where it's required and no error handling where it's not required. In general, you should be able to use `Guarantee`s and `Promise`s interchangeably, We have gone to great lengths to try and ensure this, so please open a ticket if you find an issue. --- If you are creating your own guarantees the syntax is simpler than that of promises; ```swift func fetch() -> Promise { return Guarantee { seal in fetch { result in seal(result) } } } ``` Which could be reduced to: ```swift func fetch() -> Promise { return Guarantee(resolver: fetch) } ``` # `map`, `compactMap`, etc. `then` provides you with the result of the previous promise and requires you to return another promise. `map` provides you with the result of the previous promise and requires you to return an object or value type. `compactMap` provides you with the result of the previous promise and requires you to return an `Optional`. If you return `nil`, the chain fails with `PMKError.compactMap`. > *Rationale*: Before PromiseKit 4, `then` handled all these cases, and it was painful. We hoped the pain would disappear with new Swift versions. However, it has become clear that the various pain points are here to stay. In fact, we as library authors are expected to disambiguate at the naming level of our API. Therefore, we have split the three main kinds of `then` into `then`, `map` and `done`. After using these new functions, we realized this is much nicer in practice, so we added `compactMap` as well (modeled on `Optional.compactMap`). `compactMap` facilitates quick composition of promise chains. For example: ```swift firstly { URLSession.shared.dataTask(.promise, with: rq) }.compactMap { try JSONSerialization.jsonObject($0.data) as? [String] }.done { arrayOfStrings in //… }.catch { error in // Foundation.JSONError if JSON was badly formed // PMKError.compactMap if JSON was of different type } ``` > *Tip*: We also provide most of the functional methods you would expect for sequences, e.g., `map`, `thenMap`, `compactMapValues`, `firstValue`, etc. # `get` We provide `get` as a `done` that returns the value fed to `get`. ```swift firstly { foo() }.get { foo in //… }.done { foo in // same foo! } ``` # `tap` We provide `tap` for debugging. It's the same as `get` but provides the `Result` of the `Promise` so you can inspect the value of the chain at this point without causing any side effects: ```swift firstly { foo() }.tap { print($0) }.done { //… }.catch { //… } ``` # Supplement ## `firstly` We've used `firstly` several times on this page, but what is it, really? In fact, it is just [syntactic sugar](https://en.wikipedia.org/wiki/Syntactic_sugar). You don’t really need it, but it helps to make your chains more readable. Instead of: ```swift firstly { login() }.then { creds in //… } ``` You could just do: ```swift login().then { creds in //… } ``` Here is a key understanding: `login()` returns a `Promise`, and all `Promise`s have a `then` function. `firstly` returns a `Promise`, and `then` returns a `Promise`, too! But don’t worry too much about these details. Learn the *patterns* to start with. Then, when you are ready to advance, learn the underlying architecture. ## `when` Variants `when` is one of PromiseKit’s more useful functions, and so we offer several variants. * The default `when`, and the one you should typically use, is `when(fulfilled:)`. This variant waits on all its component promises, but if any fail, `when` fails too, and thus the chain *rejects*. It's important to note that all promises in the `when` *continue*. Promises have *no* control over the tasks they represent. Promises are just wrappers around tasks. * `when(resolved:)` waits even if one or more of its component promises fails. The value produced by this variant of `when` is an array of `Result`. Consequently, this variant requires all its component promises to have the same generic type. See our advanced patterns guide for work-arounds for this limitation. * The `race` variant lets you *race* several promises. Whichever finishes first is the result. See the advanced patterns guide for typical usage. ## Swift Closure Inference Swift automatically infers returns and return types for one-line closures. The following two forms are the same: ```swift foo.then { bar($0) } // is the same as: foo.then { baz -> Promise in return bar(baz) } ``` Our documentation often omits the `return` for clarity. However, this shorthand is both a blessing and a curse. You may find that the Swift compiler often fails to infer return types properly. See our [Troubleshooting Guide](Troubleshooting.md) if you require further assistance. > By adding `done` to PromiseKit 5, we have managed to avoid many of these common pain points in using PromiseKit and Swift. # Further Reading The above information is the 90% you will use. We **strongly** suggest reading the [API Reference]. There are numerous little functions that may be useful to you, and the documentation for everything outlined above is more thorough at the source. In Xcode, don’t forget to option-click on PromiseKit functions to access this documentation while you're coding. Here are some recent articles that document PromiseKit 5+: * [Using Promises - Agostini.tech](https://agostini.tech/2018/10/08/using-promisekit) Careful with general online references, many of them refer to PMK < 5 which has a subtly different API (sorry about that, but Swift has changed a lot over the years and thus we had to too). [API Reference]: https://mxcl.dev/PromiseKit/reference/v6/Classes/Promise.html ================================================ FILE: Documentation/Installation.md ================================================ # Xcode 8.3, 9.x or 10.x / Swift 3 or 4 We recommend Carthage over CocoaPods, but both installation methods are supported. ## CocoaPods ```ruby use_frameworks! target "Change Me!" do pod "PromiseKit", "~> 6.8" end ``` If the generated Xcode project gives you a warning that PromiseKit needs to be upgraded to Swift 4.0 or Swift 4.2, then add the following: ```ruby post_install do |installer| installer.pods_project.targets.each do |target| if target.name == 'PromiseKit' target.build_configurations.each do |config| config.build_settings['SWIFT_VERSION'] = '4.2' end end end end ``` Adjust the value for `SWIFT_VERSION` as needed. CocoaPods are aware of this [issue](https://github.com/CocoaPods/CocoaPods/issues/7134). ## Carthage ```ruby github "mxcl/PromiseKit" ~> 6.8 ``` > Please note, since PromiseKit 6.8.1 our Carthage support has transitioned to > Swift 4 and above only. Strictly we *do* still support Swift 3.1 for Carthage, > and if you like you could edit the PromiseKit `project.pbxproj` file during > `carthage bootstrap` to make this possible. This change was involuntary and due > to Xcode 10.2 dropping support for Swift 3. From Xcode 12, you will likely need to build using `--use-xcframeworks`, eg: carthage build --use-xcframeworks ## Accio Add the following to your Package.swift: ```swift .package(url: "https://github.com/mxcl/PromiseKit.git", .upToNextMajor(from: "6.8.4")), ``` Next, add `PromiseKit` to your App targets dependencies like so: ```swift .target( name: "App", dependencies: [ "PromiseKit", ] ), ``` Then run `accio update`. ## SwiftPM ```swift package.dependencies.append( .package(url: "https://github.com/mxcl/PromiseKit", from: "6.8.0") ) ``` ## Manually You can just drop `PromiseKit.xcodeproj` into your project and then add `PromiseKit.framework` to your app’s embedded frameworks. # PromiseKit vs. Xcode PromiseKit contains Swift, so there have been rev-lock issues with Xcode: | PromiseKit | Swift | Xcode | CI Status | Release Notes | | ---------- | ----------------------- | -------- | ------------ | ----------------- | | 6 | 3.2, 3.3, 4.x, 5.x | 8.3, 9.x, 10.x | ![ci-master] | [2018/02][news-6] | | 5 | 3.1, 3.2, 3.3, 4.x | 8.3, 9.x, 10.1 | *Deprecated* | *n/a* | | 4 | 3.0, 3.1, 3.2, 3.3, 4.x | 8.x, 9.x, 10.1 | ![ci-master] | [2016/09][news-4] | | 3 | 2.x | 7.x, 8.0 | ![ci-swift2] | [2015/10][news-3] | | 2 | 1.x | 7.x | *Deprecated* | [2015/10][news-3] | | 1† | *N/A* | * | ![ci-legacy] | – | † PromiseKit 1 is pure Objective-C and thus can be used with any Xcode, it is also your only choice if you need to support iOS 7 or below. --- We also maintain a series of branches to aid migration for PromiseKit 2: | Xcode | Swift | PromiseKit | Branch | CI Status | | ----- | ----- | -----------| --------------------------- | --------- | | 8.0 | 2.3 | 2 | [swift-2.3-minimal-changes] | ![ci-23] | | 7.3 | 2.2 | 2 | [swift-2.2-minimal-changes] | ![ci-22] | | 7.2 | 2.2 | 2 | [swift-2.2-minimal-changes] | ![ci-22] | | 7.1 | 2.1 | 2 | [swift-2.0-minimal-changes] | ![ci-20] | | 7.0 | 2.0 | 2 | [swift-2.0-minimal-changes] | ![ci-20] | We do **not** usually backport fixes to these branches, but pull requests are welcome. ## Xcode 8 / Swift 2.3 or Xcode 7 ```ruby # CocoaPods swift_version = "2.3" pod "PromiseKit", "~> 3.5" # Carthage github "mxcl/PromiseKit" ~> 3.5 ``` [travis]: https://travis-ci.org/mxcl/PromiseKit [ci-master]: https://travis-ci.org/mxcl/PromiseKit.svg?branch=master [ci-legacy]: https://travis-ci.org/mxcl/PromiseKit.svg?branch=legacy-1.x [ci-swift2]: https://travis-ci.org/mxcl/PromiseKit.svg?branch=swift-2.x [ci-23]: https://travis-ci.org/mxcl/PromiseKit.svg?branch=swift-2.3-minimal-changes [ci-22]: https://travis-ci.org/mxcl/PromiseKit.svg?branch=swift-2.2-minimal-changes [ci-20]: https://travis-ci.org/mxcl/PromiseKit.svg?branch=swift-2.0-minimal-changes [news-2]: http://mxcl.dev/PromiseKit/news/2015/05/PromiseKit-2.0-Released/ [news-3]: https://github.com/mxcl/PromiseKit/blob/212f31f41864d1e3ec54f5dd529bd8e1e5697024/CHANGELOG.markdown#300-oct-1st-2015 [news-4]: http://mxcl.dev/PromiseKit/news/2016/09/PromiseKit-4.0-Released/ [news-6]: http://mxcl.dev/PromiseKit/news/2018/02/PromiseKit-6.0-Released/ [swift-2.3-minimal-changes]: https://github.com/mxcl/PromiseKit/tree/swift-2.3-minimal-changes [swift-2.2-minimal-changes]: https://github.com/mxcl/PromiseKit/tree/swift-2.2-minimal-changes [swift-2.0-minimal-changes]: https://github.com/mxcl/PromiseKit/tree/swift-2.0-minimal-changes # Using Git Submodules for PromiseKit’s Extensions > *Note*: This is a more advanced technique. If you use CocoaPods and a few PromiseKit extensions, then importing PromiseKit causes that module to import all the extension frameworks. Thus, if you have an app and a few app extensions (e.g., iOS app, iOS watch extension, iOS Today extension) then all your final products that use PromiseKit will have forced dependencies on all the Apple frameworks that PromiseKit provides extensions for. This isn’t that bad, but every framework that loads entails overhead and lengthens startup time. It’s both better and worse with Carthage. We build individual micro-frameworks for each PromiseKit extension, so your final products link against only the Apple frameworks that they actually need. However, Apple has advised that apps link only against “about 12” frameworks for performance reasons. So with Carthage, we are worse off on this metric. The solution is to instead import only CorePromise: ```ruby # CocoaPods pod "PromiseKit/CorePromise" # Carthage github "mxcl/PromiseKit" # ^^ for Carthage *only* have this ``` And to use the extensions you need via `git submodules`: ``` git submodule init git submodule add https://github.com/PromiseKit/UIKit Submodules/PMKUIKit ``` Then in Xcode you can add these sources to your targets on a per-target basis. Then when you `pod update`, ensure that you also update your submodules: pod update && git submodule update --recursive --remote # Release History ## [6.0](https://github.com/mxcl/PromiseKit/releases/tag/6.0.0) Feb 13th, 2018 * [PromiseKit 6 announcement post][news-6]. ## [4.0](https://github.com/mxcl/PromiseKit/releases/tag/4.0.0) * [PromiseKit 4 announcement post][news-4]. ## [3.0](https://github.com/mxcl/PromiseKit/releases/tag/3.0.0) Oct 1st, 2015 In Swift 2.0 `catch` and `defer` became reserved keywords mandating we rename our functions with these names. This forced a major semantic version change on PromiseKit and thus we took the opportunity to make other minor (source compatibility breaking) improvements. Thus if you cannot afford to adapt to PromiseKit 3 but still want to use Xcode-7.0/Swift-2.0 we provide a [minimal changes branch] where `catch` and `defer` are renamed `catch_` and `defer_` and all other changes are the bare minimum to make PromiseKit 2 compile against Swift 2. If you still are using Xcode 6 and Swift 1.2 then use PromiseKit 2. [minimal changes branch]: https://github.com/mxcl/PromiseKit/tree/swift-2.0-minimal-changes ## [2.0](https://github.com/mxcl/PromiseKit/releases/tag/2.0.0) May 14th, 2015 [PromiseKit 2 announcement post](http://mxcl.dev/PromiseKit/news/2015/05/PromiseKit-2.0-Released/). ## [1.5](https://github.com/mxcl/PromiseKit/releases/tag/1.5.0) Swift 1.2 support. Xcode 6.3 required. ================================================ FILE: Documentation/ObjectiveC.md ================================================ # Objective-C PromiseKit has two promise classes: * `Promise` (Swift) * `AnyPromise` (Objective-C) Each is designed to be an appropriate promise implementation for the strong points of its language: * `Promise` is strict, defined and precise. * `AnyPromise` is loose and dynamic. Unlike most libraries, we have extensive bridging support, you can use PromiseKit in mixed projects with mixed language targets and mixed language libraries. # Using PromiseKit with Objective-C `AnyPromise` is our promise class for Objective-C. It behaves almost identically to `Promise`, our Swift promise class. ```objc myPromise.then(^(NSString *bar){ return anotherPromise; }).then(^{ //… }).catch(^(NSError *error){ //… }); ``` You make new promises using `promiseWithResolverBlock`: ```objc - (AnyPromise *)myPromise { return [AnyPromise promiseWithResolverBlock:^(PMKResolver resolve){ resolve(foo); // if foo is an NSError, rejects, else, resolves }]; } ``` --- You reject promises by throwing errors: ```objc myPromise.then(^{ @throw [NSError errorWithDomain:domain code:code userInfo:nil]; }).catch(^(NSError *error){ //… }); ``` One important feature is the syntactic flexibility of your handlers: ```objc myPromise.then(^{ // no parameters is fine }); myPromise.then(^(id foo){ // one parameter is fine }); myPromise.then(^(id a, id b, id c){ // up to three parameter is fine, no crash! }); myPromise.then(^{ return @1; // return anything or nothing, it's fine, no crash }); ``` We do runtime inspection of the block you pass to achieve this magic. --- Another important distinction is that the equivalent function to Swift’s `recover` is combined with `AnyPromise`’s `catch`. This is typical to other “dynamic” promise implementations and thus achieves our goal that `AnyPromise` is loose and dynamic while `Promise` is strict and specific. A sometimes unexpected consequence of this fact is that returning nothing from a `catch` *resolves* the returned promise: ```objc myPromise.catch(^{ [UIAlertView …]; }).then(^{ // always executes! }); ``` --- Another important distinction is that the `value` property returns even if the promise is rejected; in that case, it returns the `NSError` object with which the promise was rejected. # Bridging Between Objective-C & Swift Let’s say you have: ```objc @interface Foo - (AnyPromise *)myPromise; @end ``` Ensure that this interface is included in your bridging header. You can now use the following pattern in your Swift code: ```swift let foo = Foo() foo.myPromise.then { (obj: AnyObject?) -> Int in // it is not necessary to specify the type of `obj` // we just do that for demonstrative purposes } ``` --- Let’s say you have: ```swift @objc class Foo: NSObject { func stringPromise() -> Promise func barPromise() -> Promise } @objc class Bar: NSObject { /*…*/ } ``` Ensure that your project is generating a `…-Swift.h` header so that Objective-C can see your Swift code. If you built this project and opened the `…-Swift.h` header, you would only see this: ```objc @interface Foo @end @interface Bar @end ``` That's because Objective-C cannot import Swift objects that are generic. So we need to write some stubs: ```swift @objc class Foo: NSObject { @objc func stringPromise() -> AnyPromise { return AnyPromise(stringPromise()) } @objc func barPromise() -> AnyPromise { return AnyPromise(barPromise()) } } ``` If we built this and opened our generated header, we would now see: ```objc @interface Foo - (AnyPromise *)stringPromise; - (AnyPromise *)barPromise; @end @interface Bar @end ``` Perfect. Note that AnyPromise can only bridge objects that conform to `AnyObject` or derive from `NSObject`. This is a limitation of Objective-C. # Using ObjC AnyPromises from Swift Simply use them, the type of your handler parameter is `Any`: ```objective-c - (AnyPromise *)fetchThings { return [AnyPromise promiseWithValue:@[@"a", @"b", @"c"]]; } ``` Since ObjC is not type-safe and Swift is, you will (probably) need to cast the `Any` to whatever it is you actually are feeding: ```swift Foo.fetchThings().done { any in let bar = any as! [String] } ``` ## :warning: Caution: ARC in Objective-C, unlike in Objective-C++, is not exception-safe by default. So, throwing an error will result in keeping a strong reference to the closure that contains the throw statement. This pattern will consequently result in memory leaks if you're not careful. > *Note:* Only having a strong reference to the closure would result in memory leaks. > In our case, PromiseKit automatically keeps a strong reference to the closure until it's released. __Workarounds:__ 1. Return a Promise with value NSError\ Instead of throwing a normal error, you can return a Promise with value NSError instead. ```objc myPromise.then(^{ return [AnyPromise promiseWithValue:[NSError myCustomError]]; }).catch(^(NSError *error){ if ([error isEqual:[NSError myCustomError]]) { // In case, same error as the one we thrown return; } //… }); ``` 2. Enable ARC for exceptions in Objective-C (not recommended)\ You can add this ```-fobjc-arc-exceptions to your``` to your compiler flags to enable ARC for exceptions. This is not recommended unless you've read the Apple documentation and are comfortable with the caveats. For more details on ARC and exceptions: https://clang.llvm.org/docs/AutomaticReferenceCounting.html#exceptions ================================================ FILE: Documentation/README.md ================================================ # Contents * [README](../README.md) * Handbook * [Getting Started](GettingStarted.md) * [Promises: Common Patterns](CommonPatterns.md) * [Frequently Asked Questions](FAQ.md) * Manual * [Installation Guide](Installation.md) * [Objective-C Guide](ObjectiveC.md) * [Troubleshooting](Troubleshooting.md) * [Appendix](Appendix.md) * [Examples](Examples) * [API Reference](https://mxcl.dev/PromiseKit/reference/v6/Classes/Promise.html) ================================================ FILE: Documentation/Troubleshooting.md ================================================ # Troubleshooting ## Compilation errors 99% of compilation issues involving PromiseKit can be addressed or diagnosed by one of the fixes below. ### Check your handler ```swift return firstly { URLSession.shared.dataTask(.promise, with: url) }.compactMap { JSONSerialization.jsonObject(with: $0.data) as? [String: Any] }.then { dict in User(dict: dict) } ``` Swift (unhelpfully) says: > Cannot convert value of type '([String : Any]) -> User' to expected argument type '([String : Any]) -> _' What’s the real problem? `then` *must* return a `Promise`, and you're trying to return something else. What you really want is `map`: ```swift return firstly { URLSession.shared.dataTask(.promise, with: url) }.compactMap { JSONSerialization.jsonObject(with: $0.data) as? [String: Any] }.map { dict in User(dict: dict) } ``` ### Specify closure parameters **and** return type For example: ```swift return firstly { foo() }.then { user in //… return bar() } ``` This code may compile if you specify the type of `user`: ```swift return firstly { foo() }.then { (user: User) in //… return bar() } ``` If it still doesn't compile, perhaps you need to specify the return type, too: ```swift return firstly { foo() }.then { (user: User) -> Promise in //… return bar() } ``` We have made great effort to reduce the need for explicit typing in PromiseKit 6, but as with all Swift functions that return a generic type (e.g., `Array.map`), you may need to explicitly tell Swift what a closure returns if the closure's body is longer than one line. > *Tip*: Sometimes you can force a one-liner by using semicolons. ### Acknowledge all incoming closure parameters Swift does not permit you to silently ignore a closure's parameters. For example, this code: ```swift func _() -> Promise { return firstly { proc.launch(.promise) // proc: Foundation.Process }.then { when(fulfilled: p1, p2) // both p1 & p2 are `Promise` } } ``` Fails to compile with the error: Cannot invoke 'then' with an argument list of type '(() -> _) What's the problem? Well, `Process.launch(.promise)` returns `Promise<(String, String)>`, and we are ignoring this value in our `then` closure. If we’d referenced `$0` or named the parameter, Swift would have been satisfied. Assuming that we really do want to ignore the argument, the fix is to explicitly acknowledge its existence by assigning it the name "_". That's Swift-ese for "I know there's a value here, but I'm ignoring it." ```swift func _() -> Promise { return firstly { proc.launch(.promise) }.then { _ in when(fulfilled: p1, p2) } } ``` In this situation, you won't always receive an error message that's as clear as the one shown above. Sometimes, a missing closure parameter sends Swift scurrying off into type inference limbo. When it finally concludes that there's no way for it to make all the inferred types work together, it may end up assigning blame to some other closure entirely and giving you an error message that makes no sense at all. When faced with this kind of enigmatic complaint, a good rule of thumb is to double-check your argument and return types carefully. If everything looks OK, temporarily add explicit type information as shown above, just to rule out misinference as a possible cause. ### Try moving code to a temporary inline function Try taking the code out of a closure and putting it in a standalone function. Now Swift will give you the *real* error message. For example: ```swift func doStuff() { firstly { foo() }.then { let bar = bar() let baz = baz() when(fulfilled: bar, baz) } } ``` Becomes: ```swift func doStuff() { func fluff() -> Promise<…> { let bar = bar() let baz = baz() when(fulfilled: bar, baz) } firstly { foo() }.then { fluff() } } ``` An *inline* function like this is all you need. Here, the problem is that you forgot to mark the last line of the closure with an explicit `return`. It's required here because the closure is longer than one line. ## You copied code off the Internet that doesn’t work Swift has changed a lot over the years and so PromiseKit has had to change to keep up. The code you copied is probably for an older PromiseKit. *Read the definitions of the functions.* It's easy to do this in Xcode by option-clicking or command-clicking function names. All PromiseKit functions are documented and provide examples. ## "Context type for closure argument expects 1 argument, which cannot be implicitly ignored" You have a `then`; you want a `done`. ## "Missing argument for parameter #1 in call" This is part of Swift 4’s “tuplegate”. You must specify your `Void` parameter: ```swift seal.fulfill(()) ``` Yes: we hope they revert this change in Swift 5 too. ## "Ambiguous reference to 'firstly(execute:)'" Remove the firstly, e.g.: ```swift firstly { foo() }.then { //… } ``` becomes: ```swift foo().then { //… } ``` Rebuild and Swift should now tell you the *real* error. ## Other issues ### `Pending Promise Deallocated!` If you see this warning, you have a path in your `Promise` initializer that allows the promise to escape without being sealed: ```swift Promise { seal in task { value, error in if let value = value as? String { seal.fulfill(value) } else if let error = error { seal.reject(error) } } } ``` There are two missing paths here, and if either occurs, the promise will soon be deallocated without resolving. This will manifest itself as a bug in your app, probably the awful infinite spinner. So let’s be thorough: ```swift Promise { seal in task { value, error in if let value = value as? String { fulfill(value) } else if let error = error { reject(error) } else if value != nil { reject(MyError.valueNotString) } else { // should never happen, but we have an `PMKError` for task being called with `nil`, `nil` reject(PMKError.invalidCallingConvention) } } } ``` If this seems tedious, it shouldn’t. You would have to be this thorough without promises, too. The difference is that without promises, you wouldn’t get a warning in the console notifying you of your mistake! ### Slow compilation / compiler cannot solve in reasonable time Add return types to your closures. ### My promise never resolves There are several potential causes: #### 1. Check to be sure that your asynchronous task even *starts* You’d be surprised how often this is the cause. For example, if you are using `URLSession` without our extension (but don’t do that; *use* our extension! we know all the pitfalls), did you forget to call `resume` on the task? If so, the task never actually starts, and so of course it never finishes, either. #### 2. Check that all paths in your custom Promise initializers are handled See “Pending Promise Deallocated” above. Usually you will see this warning if you are not handling a path, but that requires your promise deallocate, so you may not see this warning yet you are still not handling all paths. Unhandled paths mean the promise will not resolve. #### 3. Ensure the queue your promise handler runs upon is not blocked If the thread is blocked the handlers cannot execute. Commonly you can see this if you are using our `wait()` function. Please read the documentation for `wait()` for suggestions and caveats. #### 4. Your promise returned a cancellation error Cancelation is neither success nor failure. So this is the correct behavior. Use a `finally` if you need to do some clean up. ### `Result of call to 'done(on:_:)' is unused`, `Result of call to 'then(on:_:)' is unused` PromiseKit deliberately avoids the `@discardableResult` annotation because the unused result warning is a hint that you have not handled the error in your chain. So do one of these: 1. Add a `catch` 2. `return` the promise (thus punting the error handling to the caller) 3. Use `cauterize()` to silence the warning. Obviously, do 1 or 2 in preference to 3. ================================================ FILE: LICENSE ================================================ Copyright 2016-present, Max Howell; mxcl@me.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: Package.swift ================================================ // swift-tools-version:4.0 import PackageDescription let pkg = Package(name: "PromiseKit") pkg.products = [ .library(name: "PromiseKit", targets: ["PromiseKit"]), ] let pmk: Target = .target(name: "PromiseKit") pmk.path = "Sources" pmk.exclude = [ "AnyPromise.swift", "AnyPromise.m", "PMKCallVariadicBlock.m", "dispatch_promise.m", "join.m", "when.m", "NSMethodSignatureForBlock.m", "after.m", "hang.m", "race.m", "Deprecations.swift" ] pkg.swiftLanguageVersions = [3, 4, 5] pkg.targets = [ pmk, .testTarget(name: "APlus", dependencies: ["PromiseKit"], path: "Tests/A+"), .testTarget(name: "CorePromise", dependencies: ["PromiseKit"], path: "Tests/CorePromise"), ] ================================================ FILE: Package@swift-4.2.swift ================================================ // swift-tools-version:4.2 import PackageDescription let pkg = Package(name: "PromiseKit") pkg.products = [ .library(name: "PromiseKit", targets: ["PromiseKit"]), ] let pmk: Target = .target(name: "PromiseKit") pmk.path = "Sources" pmk.exclude = [ "AnyPromise.swift", "AnyPromise.m", "PMKCallVariadicBlock.m", "dispatch_promise.m", "join.m", "when.m", "NSMethodSignatureForBlock.m", "after.m", "hang.m", "race.m", "Deprecations.swift" ] pkg.swiftLanguageVersions = [.v3, .v4, .v4_2] pkg.targets = [ pmk, .testTarget(name: "APlus", dependencies: ["PromiseKit"], path: "Tests/A+"), .testTarget(name: "CorePromise", dependencies: ["PromiseKit"], path: "Tests/CorePromise"), ] ================================================ FILE: Package@swift-5.0.swift ================================================ // swift-tools-version:5.0 import PackageDescription let pkg = Package(name: "PromiseKit") pkg.platforms = [ .macOS(.v10_10), .iOS(.v8), .tvOS(.v9), .watchOS(.v2) ] pkg.products = [ .library(name: "PromiseKit", targets: ["PromiseKit"]), ] let pmk: Target = .target(name: "PromiseKit") pmk.path = "Sources" pmk.exclude = [ "AnyPromise.swift", "AnyPromise.m", "PMKCallVariadicBlock.m", "dispatch_promise.m", "join.m", "when.m", "NSMethodSignatureForBlock.m", "after.m", "hang.m", "race.m", "Deprecations.swift" ] pkg.swiftLanguageVersions = [.v4, .v4_2, .v5] pkg.targets = [ pmk, .testTarget(name: "APlus", dependencies: ["PromiseKit"], path: "Tests/A+"), .testTarget(name: "CorePromise", dependencies: ["PromiseKit"], path: "Tests/CorePromise"), ] ================================================ FILE: Package@swift-5.3.swift ================================================ // swift-tools-version:5.3 import PackageDescription let pkg = Package(name: "PromiseKit") pkg.platforms = [ .macOS(.v10_10), .iOS(.v9), .tvOS(.v9), .watchOS(.v2) ] pkg.products = [ .library(name: "PromiseKit", targets: ["PromiseKit"]), ] let pmk: Target = .target(name: "PromiseKit") pmk.path = "Sources" pmk.resources = [ .process("Resources/PrivacyInfo.xcprivacy") ] pmk.exclude = [ "AnyPromise.swift", "AnyPromise.m", "PMKCallVariadicBlock.m", "dispatch_promise.m", "join.m", "when.m", "NSMethodSignatureForBlock.m", "after.m", "hang.m", "race.m", "Deprecations.swift", "Info.plist" ] pkg.swiftLanguageVersions = [.v4, .v4_2, .v5] pkg.targets = [ pmk, .testTarget(name: "APlus", dependencies: ["PromiseKit"], path: "Tests/A+", exclude: ["README.md"]), .testTarget(name: "CorePromise", dependencies: ["PromiseKit"], path: "Tests/CorePromise"), ] ================================================ FILE: PromiseKit.playground/Contents.swift ================================================ import PlaygroundSupport // Is this erroring? If so open the `.xcodeproj` and build the // framework for a macOS target (usually labeled: “My Mac”). // Then select `PromiseKit.playground` from inside Xcode. import PromiseKit func promise3() -> Promise { return after(.seconds(1)).map{ 3 } } firstly { Promise.value(1) }.map { _ in 2 }.then { _ in promise3() }.done { print($0) // => 3 }.catch { error in // only happens for errors }.finally { PlaygroundPage.current.finishExecution() } PlaygroundPage.current.needsIndefiniteExecution = true ================================================ FILE: PromiseKit.playground/contents.xcplayground ================================================ ================================================ FILE: PromiseKit.playground/playground.xcworkspace/contents.xcworkspacedata ================================================ ================================================ FILE: PromiseKit.podspec ================================================ Pod::Spec.new do |s| s.name = "PromiseKit" s.version = '8.2.0' s.source = { :git => "https://github.com/mxcl/#{s.name}.git", :tag => s.version, :submodules => true } s.license = 'MIT' s.summary = 'Promises for Swift & ObjC.' s.homepage = 'http://mxcl.dev/PromiseKit/' s.description = 'A thoughtful and complete implementation of promises for iOS, macOS, watchOS and tvOS with first-class support for both Objective-C and Swift.' s.social_media_url = 'https://twitter.com/mxcl' s.authors = { 'Max Howell' => 'mxcl@me.com' } s.documentation_url = 'http://mxcl.dev/PromiseKit/reference/v6/Classes/Promise.html' s.default_subspecs = 'CorePromise', 'UIKit', 'Foundation' s.requires_arc = true s.swift_version = '3.2', '3.3', '3.4', '4.0', '4.1', '4.2', '4.3', '4.4', '5.0', '5.1', '5.2', '5.3', '5.4', '5.5' # CocoaPods requires us to specify the root deployment targets # even though for us it is nonsense. Our root spec has no # sources. s.ios.deployment_target = '10.0' s.osx.deployment_target = '10.13' s.watchos.deployment_target = '4.0' s.tvos.deployment_target = '10.0' s.visionos.deployment_target = '1.0' s.pod_target_xcconfig = { 'OTHER_SWIFT_FLAGS' => '-DPMKCocoaPods', } s.resource_bundles = { 'PromiseKit_Privacy' => 'Sources/Resources/PrivacyInfo.xcprivacy' } s.subspec 'Accounts' do |ss| ss.ios.source_files = ss.osx.source_files = 'Extensions/Accounts/Sources/**/*' ss.exclude_files = 'Extensions/Accounts/Sources/*.plist' ss.ios.frameworks = ss.osx.frameworks = 'Accounts' ss.dependency 'PromiseKit/CorePromise' ss.ios.deployment_target = '10.0' ss.osx.deployment_target = '10.13' end s.subspec 'AddressBook' do |ss| ss.ios.source_files = 'Extensions/AddressBook/Sources/**/*' ss.exclude_files = 'Extensions/AddressBook/Sources/*.plist' ss.ios.frameworks = 'AddressBook' ss.dependency 'PromiseKit/CorePromise' ss.ios.deployment_target = '10.0' end s.subspec 'AssetsLibrary' do |ss| ss.ios.source_files = 'Extensions/AssetsLibrary/Sources/**/*' ss.exclude_files = 'Extensions/AssetsLibrary/Sources/*.plist' ss.ios.frameworks = 'AssetsLibrary' ss.dependency 'PromiseKit/CorePromise' ss.ios.deployment_target = '10.0' end s.subspec 'AVFoundation' do |ss| ss.ios.source_files = 'Extensions/AVFoundation/Sources/**/*' ss.exclude_files = 'Extensions/AVFoundation/Sources/*.plist' ss.ios.frameworks = 'AVFoundation' ss.dependency 'PromiseKit/CorePromise' ss.ios.deployment_target = '10.0' end s.subspec 'CloudKit' do |ss| ss.source_files = 'Extensions/CloudKit/Sources/**/*' ss.exclude_files = 'Extensions/CloudKit/Sources/*.plist' ss.frameworks = 'CloudKit' ss.dependency 'PromiseKit/CorePromise' ss.ios.deployment_target = '10.0' ss.osx.deployment_target = '10.13' ss.tvos.deployment_target = '10.0' ss.watchos.deployment_target = '4.0' end s.subspec 'CoreBluetooth' do |ss| ss.ios.source_files = ss.osx.source_files = ss.tvos.source_files = 'Extensions/CoreBluetooth/Sources/**/*' ss.exclude_files = 'Extensions/CoreBluetooth/Sources/*.plist' ss.ios.frameworks = ss.osx.frameworks = ss.tvos.frameworks = 'CoreBluetooth' ss.dependency 'PromiseKit/CorePromise' ss.ios.deployment_target = '10.0' ss.osx.deployment_target = '10.13' ss.tvos.deployment_target = '10.0' end s.subspec 'CorePromise' do |ss| hh = Dir['Sources/*.h'] - Dir['Sources/*+Private.h'] cc = Dir['Sources/*.swift'] - ['Sources/SwiftPM.swift'] cc << 'Sources/{after,AnyPromise,GlobalState,dispatch_promise,hang,join,PMKPromise,when,race}.m' cc += hh ss.source_files = cc ss.exclude_files = 'Sources/*.plist' ss.public_header_files = hh ss.preserve_paths = 'Sources/AnyPromise+Private.h', 'Sources/PMKCallVariadicBlock.m', 'Sources/NSMethodSignatureForBlock.m' ss.frameworks = 'Foundation' ss.ios.deployment_target = '10.0' ss.osx.deployment_target = '10.13' ss.watchos.deployment_target = '4.0' ss.tvos.deployment_target = '10.0' end s.subspec 'CoreLocation' do |ss| ss.source_files = 'Extensions/CoreLocation/Sources/**/*' ss.exclude_files = 'Extensions/CoreLocation/Sources/*.plist' ss.watchos.source_files = 'Extensions/CoreLocation/Sources/CLGeocoder*' ss.dependency 'PromiseKit/CorePromise' ss.frameworks = 'CoreLocation' ss.ios.deployment_target = '10.0' ss.osx.deployment_target = '10.13' ss.watchos.deployment_target = '4.0' ss.tvos.deployment_target = '10.0' end s.subspec 'EventKit' do |ss| ss.ios.source_files = ss.osx.source_files = ss.watchos.source_files = 'Extensions/EventKit/Sources/**/*' ss.exclude_files = 'Extensions/EventKit/Sources/*.plist' ss.ios.frameworks = ss.osx.frameworks = ss.watchos.frameworks = 'EventKit' ss.dependency 'PromiseKit/CorePromise' ss.ios.deployment_target = '10.0' ss.osx.deployment_target = '10.13' ss.watchos.deployment_target = '4.0' end s.subspec 'Foundation' do |ss| ss.source_files = Dir['Extensions/Foundation/Sources/**/*'] ss.exclude_files = 'Extensions/Foundation/Sources/*.plist' ss.dependency 'PromiseKit/CorePromise' ss.frameworks = 'Foundation' ss.ios.deployment_target = '10.0' ss.osx.deployment_target = '10.13' ss.watchos.deployment_target = '4.0' ss.tvos.deployment_target = '10.0' end s.subspec 'HealthKit' do |ss| ss.source_files = Dir['Extensions/HealthKit/Sources/**/*'] ss.exclude_files = 'Extensions/HealthKit/Sources/*.plist' ss.dependency 'PromiseKit/CorePromise' ss.frameworks = 'HealthKit' ss.ios.deployment_target = '10.0' ss.watchos.deployment_target = '4.0' end s.subspec 'HomeKit' do |ss| ss.source_files = Dir['Extensions/HomeKit/Sources/**/*'] ss.exclude_files = 'Extensions/HomeKit/Sources/*.plist' ss.dependency 'PromiseKit/CorePromise' ss.frameworks = 'HomeKit' ss.ios.deployment_target = '10.0' ss.watchos.deployment_target = '4.0' ss.tvos.deployment_target = '10.0' end s.subspec 'MapKit' do |ss| ss.ios.source_files = ss.osx.source_files = ss.tvos.source_files = 'Extensions/MapKit/Sources/**/*' ss.exclude_files = 'Extensions/MapKit/Sources/*.plist' ss.ios.frameworks = ss.osx.frameworks = ss.tvos.frameworks = 'MapKit' ss.dependency 'PromiseKit/CorePromise' ss.ios.deployment_target = '10.0' ss.osx.deployment_target = '10.13' ss.watchos.deployment_target = '4.0' ss.tvos.deployment_target = '10.0' end s.subspec 'MessageUI' do |ss| ss.ios.source_files = 'Extensions/MessagesUI/Sources/**/*' ss.exclude_files = 'Extensions/MessagesUI/Sources/*.plist' ss.ios.frameworks = 'MessageUI' ss.dependency 'PromiseKit/CorePromise' ss.ios.deployment_target = '10.0' end s.subspec 'Photos' do |ss| ss.ios.source_files = ss.tvos.source_files = ss.osx.source_files = 'Extensions/Photos/Sources/**/*' ss.exclude_files = 'Extensions/Photos/Sources/*.plist' ss.ios.frameworks = ss.tvos.frameworks = ss.osx.frameworks = 'Photos' ss.dependency 'PromiseKit/CorePromise' ss.ios.deployment_target = '10.0' ss.osx.deployment_target = '10.13' ss.tvos.deployment_target = '10.0' end s.subspec 'QuartzCore' do |ss| ss.osx.source_files = ss.ios.source_files = ss.tvos.source_files = 'Extensions/QuartzCore/Sources/**/*' ss.exclude_files = 'Extensions/QuartzCore/Sources/*.plist' ss.osx.frameworks = ss.ios.frameworks = ss.tvos.frameworks = 'QuartzCore' ss.dependency 'PromiseKit/CorePromise' ss.ios.deployment_target = '10.0' ss.osx.deployment_target = '10.13' ss.tvos.deployment_target = '10.0' end s.subspec 'Social' do |ss| ss.ios.source_files = 'Extensions/Social/Sources/**/*' ss.exclude_files = 'Extensions/Social/Sources/*.plist' ss.osx.source_files = Dir['Extensions/Social/Sources/*'] - ['Categories/Social/Sources/*SLComposeViewController+Promise.swift'] ss.ios.frameworks = ss.osx.frameworks = 'Social' ss.dependency 'PromiseKit/Foundation' ss.ios.deployment_target = '10.0' ss.osx.deployment_target = '10.13' end s.subspec 'StoreKit' do |ss| ss.ios.source_files = ss.osx.source_files = ss.tvos.source_files = 'Extensions/StoreKit/Sources/**/*' ss.exclude_files = 'Extensions/StoreKit/Sources/*.plist' ss.ios.frameworks = ss.osx.frameworks = ss.tvos.frameworks = 'StoreKit' ss.dependency 'PromiseKit/CorePromise' ss.ios.deployment_target = '10.0' ss.osx.deployment_target = '10.13' ss.tvos.deployment_target = '10.0' end s.subspec 'SystemConfiguration' do |ss| ss.ios.source_files = ss.osx.source_files = ss.tvos.source_files = 'Extensions/SystemConfiguration/Sources/**/*' ss.exclude_files = 'Extensions/SystemConfiguration/Sources/*.plist' ss.ios.frameworks = ss.osx.frameworks = ss.tvos.frameworks = 'SystemConfiguration' ss.dependency 'PromiseKit/CorePromise' ss.ios.deployment_target = '10.0' ss.osx.deployment_target = '10.13' ss.tvos.deployment_target = '10.0' end picker_cc = 'Extensions/UIKit/Sources/UIImagePickerController+Promise.swift' s.subspec 'UIKit' do |ss| ss.ios.source_files = ss.tvos.source_files = Dir['Extensions/UIKit/Sources/**/*'] - [picker_cc] ss.exclude_files = 'Extensions/UIKit/Sources/*.plist' ss.tvos.frameworks = ss.ios.frameworks = 'UIKit' ss.dependency 'PromiseKit/CorePromise' ss.ios.deployment_target = '10.0' ss.tvos.deployment_target = '10.0' end s.subspec 'UIImagePickerController' do |ss| # Since iOS 10, App Store submissions that contain references to # UIImagePickerController (even if unused in 3rd party libraries) # are rejected unless an Info.plist key is specified, thus we # moved this code to a sub-subspec. # # This *was* a subspec of UIKit, but bizarrely CocoaPods would # include this when specifying *just* UIKit…! ss.ios.source_files = picker_cc ss.exclude_files = 'Extensions/UIKit/Sources/*.plist' ss.ios.frameworks = 'UIKit' ss.ios.xcconfig = { "GCC_PREPROCESSOR_DEFINITIONS" => '$(inherited) PMKImagePickerController=1' } ss.dependency 'PromiseKit/UIKit' ss.ios.deployment_target = '10.0' end s.subspec 'WatchConnectivity' do |ss| ss.ios.source_files = ss.watchos.source_files = 'Extensions/WatchConnectivity/Sources/**/*' ss.exclude_files = 'Extensions/WatchConnectivity/Sources/*.plist' ss.ios.frameworks = ss.watchos.frameworks = 'WatchConnectivity' ss.dependency 'PromiseKit/CorePromise' ss.ios.deployment_target = '10.0' ss.watchos.deployment_target = '4.0' end end ================================================ FILE: PromiseKit.xcodeproj/project.pbxproj ================================================ // !$*UTF8*$! { archiveVersion = 1; classes = { }; objectVersion = 46; objects = { /* Begin PBXBuildFile section */ 085B96B321A6359500E5E22F /* LoggingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 085B96B121A6358900E5E22F /* LoggingTests.swift */; }; 085B96BF21A9B37C00E5E22F /* LogEvent.swift in Sources */ = {isa = PBXBuildFile; fileRef = 085B96BE21A9B37C00E5E22F /* LogEvent.swift */; }; 0C42F31B1FCF86320051309C /* HangTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0C42F3191FCF86240051309C /* HangTests.swift */; }; 0CC3AF2B1FCF84F7000E98C9 /* hang.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0CC3AF2A1FCF84F7000E98C9 /* hang.swift */; }; 49A5584D1DC5185900E4D01B /* ResolverTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 49A5584B1DC5172F00E4D01B /* ResolverTests.swift */; }; 630A8056203CEF6800D25F23 /* AnyPromiseTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 630A8051203CEF6800D25F23 /* AnyPromiseTests.m */; settings = {COMPILER_FLAGS = "-fobjc-arc-exceptions"; }; }; 630A8057203CEF6800D25F23 /* PMKManifoldTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 630A8052203CEF6800D25F23 /* PMKManifoldTests.m */; }; 630A8058203CEF6800D25F23 /* JoinTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 630A8053203CEF6800D25F23 /* JoinTests.m */; }; 630A8059203CEF6800D25F23 /* HangTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 630A8054203CEF6800D25F23 /* HangTests.m */; }; 630A805A203CEF6800D25F23 /* WhenTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 630A8055203CEF6800D25F23 /* WhenTests.m */; }; 630A805B203CF67800D25F23 /* DefaultDispatchQueueTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 635D641B1D59635300BC0AF5 /* DefaultDispatchQueueTests.swift */; }; 631411381D59795700E24B9E /* PromiseKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 63B0AC571D595E1B00FA21D9 /* PromiseKit.framework */; }; 631411431D59797100E24B9E /* BridgingTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 6314113E1D59797100E24B9E /* BridgingTests.m */; }; 631411441D59797100E24B9E /* BridgingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6314113F1D59797100E24B9E /* BridgingTests.swift */; }; 631411451D59797100E24B9E /* Infrastructure.m in Sources */ = {isa = PBXBuildFile; fileRef = 631411411D59797100E24B9E /* Infrastructure.m */; }; 631411461D59797100E24B9E /* Infrastructure.swift in Sources */ = {isa = PBXBuildFile; fileRef = 631411421D59797100E24B9E /* Infrastructure.swift */; }; 631751A41D59766500A9DDDC /* PromiseKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 63B0AC571D595E1B00FA21D9 /* PromiseKit.framework */; }; 631751B71D59768200A9DDDC /* 0.0.0.swift in Sources */ = {isa = PBXBuildFile; fileRef = 631751AB1D59768200A9DDDC /* 0.0.0.swift */; }; 631751B81D59768200A9DDDC /* 2.1.2.swift in Sources */ = {isa = PBXBuildFile; fileRef = 631751AC1D59768200A9DDDC /* 2.1.2.swift */; }; 631751B91D59768200A9DDDC /* 2.1.3.swift in Sources */ = {isa = PBXBuildFile; fileRef = 631751AD1D59768200A9DDDC /* 2.1.3.swift */; }; 631751BA1D59768200A9DDDC /* 2.2.2.swift in Sources */ = {isa = PBXBuildFile; fileRef = 631751AE1D59768200A9DDDC /* 2.2.2.swift */; }; 631751BB1D59768200A9DDDC /* 2.2.3.swift in Sources */ = {isa = PBXBuildFile; fileRef = 631751AF1D59768200A9DDDC /* 2.2.3.swift */; }; 631751BC1D59768200A9DDDC /* 2.2.4.swift in Sources */ = {isa = PBXBuildFile; fileRef = 631751B01D59768200A9DDDC /* 2.2.4.swift */; }; 631751BD1D59768200A9DDDC /* 2.2.6.swift in Sources */ = {isa = PBXBuildFile; fileRef = 631751B11D59768200A9DDDC /* 2.2.6.swift */; }; 631751BE1D59768200A9DDDC /* 2.2.7.swift in Sources */ = {isa = PBXBuildFile; fileRef = 631751B21D59768200A9DDDC /* 2.2.7.swift */; }; 631751BF1D59768200A9DDDC /* 2.3.1.swift in Sources */ = {isa = PBXBuildFile; fileRef = 631751B31D59768200A9DDDC /* 2.3.1.swift */; }; 631751C01D59768200A9DDDC /* 2.3.2.swift in Sources */ = {isa = PBXBuildFile; fileRef = 631751B41D59768200A9DDDC /* 2.3.2.swift */; }; 631751C11D59768200A9DDDC /* 2.3.4.swift in Sources */ = {isa = PBXBuildFile; fileRef = 631751B51D59768200A9DDDC /* 2.3.4.swift */; }; 632FBBE31F33B273008F8FBB /* Catchable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 632FBBE21F33B273008F8FBB /* Catchable.swift */; }; 632FBBE51F33B338008F8FBB /* CatchableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 632FBBE41F33B338008F8FBB /* CatchableTests.swift */; }; 633027E6203CC0060037E136 /* PromiseKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 63B0AC571D595E1B00FA21D9 /* PromiseKit.framework */; }; 6330B5E11F2E991200D60528 /* Configuration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6330B5E01F2E991200D60528 /* Configuration.swift */; }; 634AAD2B1EAE517C00B17855 /* fwd.h in Headers */ = {isa = PBXBuildFile; fileRef = 634AAD2A1EAE517C00B17855 /* fwd.h */; settings = {ATTRIBUTES = (Public, ); }; }; 635D641D1D59635300BC0AF5 /* PromiseTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 635D64081D59635300BC0AF5 /* PromiseTests.swift */; }; 635D641E1D59635300BC0AF5 /* CancellableErrorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 635D64091D59635300BC0AF5 /* CancellableErrorTests.swift */; }; 635D64221D59635300BC0AF5 /* ZalgoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 635D640D1D59635300BC0AF5 /* ZalgoTests.swift */; }; 635D64231D59635300BC0AF5 /* AfterTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 635D640E1D59635300BC0AF5 /* AfterTests.swift */; }; 635D64261D59635300BC0AF5 /* WhenResolvedTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 635D64111D59635300BC0AF5 /* WhenResolvedTests.swift */; }; 635D64271D59635300BC0AF5 /* RaceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 635D64121D59635300BC0AF5 /* RaceTests.swift */; }; 635D64281D59635300BC0AF5 /* WhenConcurrentTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 635D64131D59635300BC0AF5 /* WhenConcurrentTests.swift */; }; 635D642A1D59635300BC0AF5 /* WhenTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 635D64151D59635300BC0AF5 /* WhenTests.swift */; }; 635D642B1D59635300BC0AF5 /* StressTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 635D64161D59635300BC0AF5 /* StressTests.swift */; }; 635D642C1D59635300BC0AF5 /* RegressionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 635D64171D59635300BC0AF5 /* RegressionTests.swift */; }; 635D64301D596E8500BC0AF5 /* PromiseKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 63B0AC571D595E1B00FA21D9 /* PromiseKit.framework */; }; 636A291A1F1C156B001229C2 /* Promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 636A29191F1C156B001229C2 /* Promise.swift */; }; 636A291F1F1C16FF001229C2 /* Box.swift in Sources */ = {isa = PBXBuildFile; fileRef = 636A291E1F1C16FF001229C2 /* Box.swift */; }; 636A29211F1C1716001229C2 /* Thenable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 636A29201F1C1716001229C2 /* Thenable.swift */; }; 636A29231F1C17A6001229C2 /* Guarantee.swift in Sources */ = {isa = PBXBuildFile; fileRef = 636A29221F1C17A6001229C2 /* Guarantee.swift */; }; 636A29251F1C3089001229C2 /* race.swift in Sources */ = {isa = PBXBuildFile; fileRef = 636A29241F1C3089001229C2 /* race.swift */; }; 636A29271F1C3927001229C2 /* Resolver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 636A29261F1C3927001229C2 /* Resolver.swift */; }; 639BF757203DF03100FA577B /* Utilities.swift in Sources */ = {isa = PBXBuildFile; fileRef = 639BF755203DF02C00FA577B /* Utilities.swift */; }; 63B0AC7F1D595E6300FA21D9 /* after.m in Sources */ = {isa = PBXBuildFile; fileRef = 63B0AC611D595E6300FA21D9 /* after.m */; }; 63B0AC801D595E6300FA21D9 /* after.swift in Sources */ = {isa = PBXBuildFile; fileRef = 63B0AC621D595E6300FA21D9 /* after.swift */; }; 63B0AC811D595E6300FA21D9 /* AnyPromise.h in Headers */ = {isa = PBXBuildFile; fileRef = 63B0AC631D595E6300FA21D9 /* AnyPromise.h */; settings = {ATTRIBUTES = (Public, ); }; }; 63B0AC821D595E6300FA21D9 /* AnyPromise.m in Sources */ = {isa = PBXBuildFile; fileRef = 63B0AC641D595E6300FA21D9 /* AnyPromise.m */; }; 63B0AC831D595E6300FA21D9 /* AnyPromise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 63B0AC651D595E6300FA21D9 /* AnyPromise.swift */; }; 63B0AC841D595E6300FA21D9 /* AnyPromise+Private.h in Headers */ = {isa = PBXBuildFile; fileRef = 63B0AC661D595E6300FA21D9 /* AnyPromise+Private.h */; settings = {ATTRIBUTES = (Private, ); }; }; 63B0AC851D595E6300FA21D9 /* dispatch_promise.m in Sources */ = {isa = PBXBuildFile; fileRef = 63B0AC671D595E6300FA21D9 /* dispatch_promise.m */; }; 63B0AC871D595E6300FA21D9 /* Error.swift in Sources */ = {isa = PBXBuildFile; fileRef = 63B0AC691D595E6300FA21D9 /* Error.swift */; }; 63B0AC891D595E6300FA21D9 /* hang.m in Sources */ = {isa = PBXBuildFile; fileRef = 63B0AC6B1D595E6300FA21D9 /* hang.m */; }; 63B0AC8B1D595E6300FA21D9 /* join.m in Sources */ = {isa = PBXBuildFile; fileRef = 63B0AC6D1D595E6300FA21D9 /* join.m */; }; 63B0AC931D595E6300FA21D9 /* PromiseKit.h in Headers */ = {isa = PBXBuildFile; fileRef = 63B0AC761D595E6300FA21D9 /* PromiseKit.h */; settings = {ATTRIBUTES = (Public, ); }; }; 63B0AC991D595E6300FA21D9 /* when.m in Sources */ = {isa = PBXBuildFile; fileRef = 63B0AC7C1D595E6300FA21D9 /* when.m */; }; 63B0AC9A1D595E6300FA21D9 /* when.swift in Sources */ = {isa = PBXBuildFile; fileRef = 63B0AC7D1D595E6300FA21D9 /* when.swift */; }; 63B18AEC1F2D205C00B79E37 /* CustomStringConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 63B18AEB1F2D205C00B79E37 /* CustomStringConvertible.swift */; }; 63B7C94B203E2B8200FBEC00 /* AnyPromiseTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 63B7C94A203E2B8200FBEC00 /* AnyPromiseTests.swift */; }; 63B912AA1F1D7B1300D49110 /* firstly.swift in Sources */ = {isa = PBXBuildFile; fileRef = 63B912A91F1D7B1300D49110 /* firstly.swift */; }; 63CF6D7A203CC66000EC8927 /* ErrorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 63CF6D79203CC66000EC8927 /* ErrorTests.swift */; }; 63CF6D7C203CCDAB00EC8927 /* GuaranteeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 63CF6D7B203CCDAB00EC8927 /* GuaranteeTests.swift */; }; 63CF6D7E203CD12700EC8927 /* DeprecationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 63648C94203CB97400EBA011 /* DeprecationTests.swift */; }; 63CF6D80203CD19200EC8927 /* ThenableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 63CF6D7F203CD19200EC8927 /* ThenableTests.swift */; }; 63D9B2EF203385FD0075C00B /* race.m in Sources */ = {isa = PBXBuildFile; fileRef = 63D9B2EE203385FD0075C00B /* race.m */; }; 63D9B2F120338D5D0075C00B /* Deprecations.swift in Sources */ = {isa = PBXBuildFile; fileRef = 63D9B2F020338D5D0075C00B /* Deprecations.swift */; }; 9E4170F9287D88C900A3B4B5 /* Async.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9E4170F8287D88C800A3B4B5 /* Async.swift */; }; 9E4170FC287D8DF900A3B4B5 /* AsyncTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9E4170FA287D8DBD00A3B4B5 /* AsyncTests.swift */; }; 9E66231626FE5A8C00FA25CB /* RaceTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 9E66231526FE5A8C00FA25CB /* RaceTests.m */; }; 9EC774272991495C00803027 /* Combine.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9EC774262991495C00803027 /* Combine.swift */; }; 9EC7742A2991498200803027 /* CombineTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9EC774282991497900803027 /* CombineTests.swift */; }; C013F7382048E3B6006B57B1 /* MockNodeEnvironment.swift in Sources */ = {isa = PBXBuildFile; fileRef = C013F7372048E3B6006B57B1 /* MockNodeEnvironment.swift */; }; C013F73A2049076A006B57B1 /* JSPromise.swift in Sources */ = {isa = PBXBuildFile; fileRef = C013F7392049076A006B57B1 /* JSPromise.swift */; }; C013F73C20494291006B57B1 /* JSAdapter.swift in Sources */ = {isa = PBXBuildFile; fileRef = C013F73B20494291006B57B1 /* JSAdapter.swift */; }; C013F740204E5064006B57B1 /* JSUtils.swift in Sources */ = {isa = PBXBuildFile; fileRef = C013F73F204E5063006B57B1 /* JSUtils.swift */; }; C0244E5E2047A6CB00ACB4AC /* PromiseKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 63B0AC571D595E1B00FA21D9 /* PromiseKit.framework */; }; C0244E692047AC9F00ACB4AC /* AllTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0244E682047AC9F00ACB4AC /* AllTests.swift */; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ 631411341D59795700E24B9E /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = 6399A3721D595D9100D65233 /* Project object */; proxyType = 1; remoteGlobalIDString = 63B0AC561D595E1B00FA21D9; remoteInfo = PromiseKit; }; 6317518D1D59766500A9DDDC /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = 6399A3721D595D9100D65233 /* Project object */; proxyType = 1; remoteGlobalIDString = 63B0AC561D595E1B00FA21D9; remoteInfo = PromiseKit; }; 633027E2203CC0060037E136 /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = 6399A3721D595D9100D65233 /* Project object */; proxyType = 1; remoteGlobalIDString = 63B0AC561D595E1B00FA21D9; remoteInfo = PromiseKit; }; 635D64041D5962F900BC0AF5 /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = 6399A3721D595D9100D65233 /* Project object */; proxyType = 1; remoteGlobalIDString = 63B0AC561D595E1B00FA21D9; remoteInfo = PromiseKit; }; C0244E502047A6CB00ACB4AC /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = 6399A3721D595D9100D65233 /* Project object */; proxyType = 1; remoteGlobalIDString = 63B0AC561D595E1B00FA21D9; remoteInfo = PromiseKit; }; /* End PBXContainerItemProxy section */ /* Begin PBXCopyFilesBuildPhase section */ C0244E6E2047AF0B00ACB4AC /* CopyFiles */ = { isa = PBXCopyFilesBuildPhase; buildActionMask = 2147483647; dstPath = ""; dstSubfolderSpec = 7; files = ( ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXCopyFilesBuildPhase section */ /* Begin PBXFileReference section */ 085B96B121A6358900E5E22F /* LoggingTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LoggingTests.swift; sourceTree = ""; }; 085B96BE21A9B37C00E5E22F /* LogEvent.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = LogEvent.swift; path = Sources/LogEvent.swift; sourceTree = ""; }; 0C42F3191FCF86240051309C /* HangTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = HangTests.swift; sourceTree = ""; }; 0CC3AF2A1FCF84F7000E98C9 /* hang.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = hang.swift; path = Sources/hang.swift; sourceTree = ""; }; 1F1DCDF72A27AB6400E7A16B /* PromiseKit.podspec */ = {isa = PBXFileReference; lastKnownFileType = text; path = PromiseKit.podspec; sourceTree = ""; }; 49A5584B1DC5172F00E4D01B /* ResolverTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ResolverTests.swift; sourceTree = ""; }; 630019221D596292003B4E30 /* PMKCoreTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = PMKCoreTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; 630A8051203CEF6800D25F23 /* AnyPromiseTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AnyPromiseTests.m; sourceTree = ""; }; 630A8052203CEF6800D25F23 /* PMKManifoldTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = PMKManifoldTests.m; sourceTree = ""; }; 630A8053203CEF6800D25F23 /* JoinTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = JoinTests.m; sourceTree = ""; }; 630A8054203CEF6800D25F23 /* HangTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HangTests.m; sourceTree = ""; }; 630A8055203CEF6800D25F23 /* WhenTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = WhenTests.m; sourceTree = ""; }; 6314113C1D59795700E24B9E /* PMKBridgeTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = PMKBridgeTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; 6314113E1D59797100E24B9E /* BridgingTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = BridgingTests.m; sourceTree = ""; }; 6314113F1D59797100E24B9E /* BridgingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = BridgingTests.swift; sourceTree = ""; }; 631411401D59797100E24B9E /* Infrastructure.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Infrastructure.h; sourceTree = ""; }; 631411411D59797100E24B9E /* Infrastructure.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = Infrastructure.m; sourceTree = ""; }; 631411421D59797100E24B9E /* Infrastructure.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Infrastructure.swift; sourceTree = ""; }; 631751A81D59766500A9DDDC /* PMKA+Tests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = "PMKA+Tests.xctest"; sourceTree = BUILT_PRODUCTS_DIR; }; 631751AB1D59768200A9DDDC /* 0.0.0.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = 0.0.0.swift; sourceTree = ""; }; 631751AC1D59768200A9DDDC /* 2.1.2.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = 2.1.2.swift; sourceTree = ""; }; 631751AD1D59768200A9DDDC /* 2.1.3.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = 2.1.3.swift; sourceTree = ""; }; 631751AE1D59768200A9DDDC /* 2.2.2.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = 2.2.2.swift; sourceTree = ""; }; 631751AF1D59768200A9DDDC /* 2.2.3.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = 2.2.3.swift; sourceTree = ""; }; 631751B01D59768200A9DDDC /* 2.2.4.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = 2.2.4.swift; sourceTree = ""; }; 631751B11D59768200A9DDDC /* 2.2.6.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = 2.2.6.swift; sourceTree = ""; }; 631751B21D59768200A9DDDC /* 2.2.7.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = 2.2.7.swift; sourceTree = ""; }; 631751B31D59768200A9DDDC /* 2.3.1.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = 2.3.1.swift; sourceTree = ""; }; 631751B41D59768200A9DDDC /* 2.3.2.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = 2.3.2.swift; sourceTree = ""; }; 631751B51D59768200A9DDDC /* 2.3.4.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = 2.3.4.swift; sourceTree = ""; }; 631751B61D59768200A9DDDC /* README.md */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = net.daringfireball.markdown; path = README.md; sourceTree = ""; }; 632FBBE21F33B273008F8FBB /* Catchable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = Catchable.swift; path = Sources/Catchable.swift; sourceTree = ""; }; 632FBBE41F33B338008F8FBB /* CatchableTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CatchableTests.swift; sourceTree = ""; }; 633027EA203CC0060037E136 /* PMKDeprecatedTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = PMKDeprecatedTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; 6330B5E01F2E991200D60528 /* Configuration.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = Configuration.swift; path = Sources/Configuration.swift; sourceTree = ""; }; 634AAD2A1EAE517C00B17855 /* fwd.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = fwd.h; path = Sources/fwd.h; sourceTree = ""; }; 635893921D5BE4E000F14B55 /* PromiseKit.playground */ = {isa = PBXFileReference; lastKnownFileType = file.playground; path = PromiseKit.playground; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; 635893941D5BE4F900F14B55 /* LICENSE */ = {isa = PBXFileReference; lastKnownFileType = text; path = LICENSE; sourceTree = ""; }; 635893951D5BE4F900F14B55 /* Package.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Package.swift; sourceTree = ""; }; 635893971D5BE4F900F14B55 /* README.md */ = {isa = PBXFileReference; lastKnownFileType = net.daringfireball.markdown; path = README.md; sourceTree = ""; }; 635D64081D59635300BC0AF5 /* PromiseTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PromiseTests.swift; sourceTree = ""; }; 635D64091D59635300BC0AF5 /* CancellableErrorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CancellableErrorTests.swift; sourceTree = ""; }; 635D640D1D59635300BC0AF5 /* ZalgoTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ZalgoTests.swift; sourceTree = ""; }; 635D640E1D59635300BC0AF5 /* AfterTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AfterTests.swift; sourceTree = ""; }; 635D64111D59635300BC0AF5 /* WhenResolvedTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = WhenResolvedTests.swift; sourceTree = ""; }; 635D64121D59635300BC0AF5 /* RaceTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RaceTests.swift; sourceTree = ""; }; 635D64131D59635300BC0AF5 /* WhenConcurrentTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = WhenConcurrentTests.swift; sourceTree = ""; }; 635D64151D59635300BC0AF5 /* WhenTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = WhenTests.swift; sourceTree = ""; }; 635D64161D59635300BC0AF5 /* StressTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StressTests.swift; sourceTree = ""; }; 635D64171D59635300BC0AF5 /* RegressionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RegressionTests.swift; sourceTree = ""; }; 635D641B1D59635300BC0AF5 /* DefaultDispatchQueueTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DefaultDispatchQueueTests.swift; sourceTree = ""; }; 63648C94203CB97400EBA011 /* DeprecationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = DeprecationTests.swift; path = Tests/DeprecationTests.swift; sourceTree = ""; }; 636A29191F1C156B001229C2 /* Promise.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = Promise.swift; path = Sources/Promise.swift; sourceTree = ""; }; 636A291E1F1C16FF001229C2 /* Box.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = Box.swift; path = Sources/Box.swift; sourceTree = ""; }; 636A29201F1C1716001229C2 /* Thenable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = Thenable.swift; path = Sources/Thenable.swift; sourceTree = ""; }; 636A29221F1C17A6001229C2 /* Guarantee.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = Guarantee.swift; path = Sources/Guarantee.swift; sourceTree = ""; }; 636A29241F1C3089001229C2 /* race.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = race.swift; path = Sources/race.swift; sourceTree = ""; }; 636A29261F1C3927001229C2 /* Resolver.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = Resolver.swift; path = Sources/Resolver.swift; sourceTree = ""; }; 639BF755203DF02C00FA577B /* Utilities.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Utilities.swift; sourceTree = ""; }; 63B0AC571D595E1B00FA21D9 /* PromiseKit.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = PromiseKit.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 63B0AC611D595E6300FA21D9 /* after.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = after.m; path = Sources/after.m; sourceTree = ""; }; 63B0AC621D595E6300FA21D9 /* after.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = after.swift; path = Sources/after.swift; sourceTree = ""; }; 63B0AC631D595E6300FA21D9 /* AnyPromise.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = AnyPromise.h; path = Sources/AnyPromise.h; sourceTree = ""; }; 63B0AC641D595E6300FA21D9 /* AnyPromise.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = AnyPromise.m; path = Sources/AnyPromise.m; sourceTree = ""; }; 63B0AC651D595E6300FA21D9 /* AnyPromise.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = AnyPromise.swift; path = Sources/AnyPromise.swift; sourceTree = ""; }; 63B0AC661D595E6300FA21D9 /* AnyPromise+Private.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = "AnyPromise+Private.h"; path = "Sources/AnyPromise+Private.h"; sourceTree = ""; }; 63B0AC671D595E6300FA21D9 /* dispatch_promise.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = dispatch_promise.m; path = Sources/dispatch_promise.m; sourceTree = ""; }; 63B0AC691D595E6300FA21D9 /* Error.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = Error.swift; path = Sources/Error.swift; sourceTree = ""; }; 63B0AC6B1D595E6300FA21D9 /* hang.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = hang.m; path = Sources/hang.m; sourceTree = ""; }; 63B0AC6C1D595E6300FA21D9 /* Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = Info.plist; path = Sources/Info.plist; sourceTree = ""; }; 63B0AC6D1D595E6300FA21D9 /* join.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = join.m; path = Sources/join.m; sourceTree = ""; }; 63B0AC6F1D595E6300FA21D9 /* NSMethodSignatureForBlock.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = NSMethodSignatureForBlock.m; path = Sources/NSMethodSignatureForBlock.m; sourceTree = ""; }; 63B0AC711D595E6300FA21D9 /* PMKCallVariadicBlock.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = PMKCallVariadicBlock.m; path = Sources/PMKCallVariadicBlock.m; sourceTree = ""; }; 63B0AC761D595E6300FA21D9 /* PromiseKit.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = PromiseKit.h; path = Sources/PromiseKit.h; sourceTree = ""; }; 63B0AC7C1D595E6300FA21D9 /* when.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = when.m; path = Sources/when.m; sourceTree = ""; }; 63B0AC7D1D595E6300FA21D9 /* when.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = when.swift; path = Sources/when.swift; sourceTree = ""; }; 63B18AEB1F2D205C00B79E37 /* CustomStringConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = CustomStringConvertible.swift; path = Sources/CustomStringConvertible.swift; sourceTree = ""; }; 63B7C94A203E2B8200FBEC00 /* AnyPromiseTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AnyPromiseTests.swift; sourceTree = ""; }; 63B912A91F1D7B1300D49110 /* firstly.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = firstly.swift; path = Sources/firstly.swift; sourceTree = ""; }; 63CF6D79203CC66000EC8927 /* ErrorTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ErrorTests.swift; sourceTree = ""; }; 63CF6D7B203CCDAB00EC8927 /* GuaranteeTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GuaranteeTests.swift; sourceTree = ""; }; 63CF6D7F203CD19200EC8927 /* ThenableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ThenableTests.swift; sourceTree = ""; }; 63D9B2EE203385FD0075C00B /* race.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; name = race.m; path = Sources/race.m; sourceTree = ""; }; 63D9B2F020338D5D0075C00B /* Deprecations.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = Deprecations.swift; path = Sources/Deprecations.swift; sourceTree = ""; }; 9E4170F8287D88C800A3B4B5 /* Async.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = Async.swift; path = Sources/Async.swift; sourceTree = ""; }; 9E4170FA287D8DBD00A3B4B5 /* AsyncTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AsyncTests.swift; sourceTree = ""; }; 9E66231526FE5A8C00FA25CB /* RaceTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = RaceTests.m; sourceTree = ""; }; 9E8028F72BDCEDBC0081E2D1 /* PrivacyInfo.xcprivacy */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xml; path = PrivacyInfo.xcprivacy; sourceTree = ""; }; 9EC774262991495C00803027 /* Combine.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = Combine.swift; path = Sources/Combine.swift; sourceTree = ""; }; 9EC774282991497900803027 /* CombineTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CombineTests.swift; sourceTree = ""; }; C013F7372048E3B6006B57B1 /* MockNodeEnvironment.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = MockNodeEnvironment.swift; path = "Tests/JS-A+/MockNodeEnvironment.swift"; sourceTree = ""; }; C013F7392049076A006B57B1 /* JSPromise.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = JSPromise.swift; path = "Tests/JS-A+/JSPromise.swift"; sourceTree = ""; }; C013F73B20494291006B57B1 /* JSAdapter.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = JSAdapter.swift; path = "Tests/JS-A+/JSAdapter.swift"; sourceTree = ""; }; C013F73F204E5063006B57B1 /* JSUtils.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = JSUtils.swift; path = "Tests/JS-A+/JSUtils.swift"; sourceTree = ""; }; C0244E622047A6CB00ACB4AC /* PMKJSA+Tests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = "PMKJSA+Tests.xctest"; sourceTree = BUILT_PRODUCTS_DIR; }; C0244E682047AC9F00ACB4AC /* AllTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = AllTests.swift; path = "Tests/JS-A+/AllTests.swift"; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ 630019181D596292003B4E30 /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( 635D64301D596E8500BC0AF5 /* PromiseKit.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; 631411371D59795700E24B9E /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( 631411381D59795700E24B9E /* PromiseKit.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; 631751A31D59766500A9DDDC /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( 631751A41D59766500A9DDDC /* PromiseKit.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; 633027E5203CC0060037E136 /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( 633027E6203CC0060037E136 /* PromiseKit.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; 63B0AC531D595E1B00FA21D9 /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( ); runOnlyForDeploymentPostprocessing = 0; }; C0244E5D2047A6CB00ACB4AC /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( C0244E5E2047A6CB00ACB4AC /* PromiseKit.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ 630A8050203CEF6800D25F23 /* CoreObjC */ = { isa = PBXGroup; children = ( 630A8051203CEF6800D25F23 /* AnyPromiseTests.m */, 63B7C94A203E2B8200FBEC00 /* AnyPromiseTests.swift */, 630A8052203CEF6800D25F23 /* PMKManifoldTests.m */, 630A8053203CEF6800D25F23 /* JoinTests.m */, 630A8054203CEF6800D25F23 /* HangTests.m */, 630A8055203CEF6800D25F23 /* WhenTests.m */, 9E66231526FE5A8C00FA25CB /* RaceTests.m */, ); name = CoreObjC; path = Tests/CoreObjC; sourceTree = ""; }; 630B60BF1F2F739E00A1AEFE /* Features */ = { isa = PBXGroup; children = ( 63B0AC611D595E6300FA21D9 /* after.m */, 63B0AC6B1D595E6300FA21D9 /* hang.m */, 63B0AC6D1D595E6300FA21D9 /* join.m */, 63B0AC7C1D595E6300FA21D9 /* when.m */, 63D9B2EE203385FD0075C00B /* race.m */, ); name = Features; sourceTree = ""; }; 630B60C01F2F73B000A1AEFE /* Headers */ = { isa = PBXGroup; children = ( 634AAD2A1EAE517C00B17855 /* fwd.h */, 63B0AC631D595E6300FA21D9 /* AnyPromise.h */, ); name = Headers; sourceTree = ""; }; 6314113D1D59797100E24B9E /* Bridging */ = { isa = PBXGroup; children = ( 6314113E1D59797100E24B9E /* BridgingTests.m */, 6314113F1D59797100E24B9E /* BridgingTests.swift */, 631411401D59797100E24B9E /* Infrastructure.h */, 631411411D59797100E24B9E /* Infrastructure.m */, 631411421D59797100E24B9E /* Infrastructure.swift */, ); name = Bridging; path = Tests/Bridging; sourceTree = ""; }; 6317518A1D59765700A9DDDC /* Core */ = { isa = PBXGroup; children = ( 9E4170FA287D8DBD00A3B4B5 /* AsyncTests.swift */, 9EC774282991497900803027 /* CombineTests.swift */, 63CF6D7F203CD19200EC8927 /* ThenableTests.swift */, 632FBBE41F33B338008F8FBB /* CatchableTests.swift */, 635D64081D59635300BC0AF5 /* PromiseTests.swift */, 49A5584B1DC5172F00E4D01B /* ResolverTests.swift */, 63CF6D7B203CCDAB00EC8927 /* GuaranteeTests.swift */, 635D64091D59635300BC0AF5 /* CancellableErrorTests.swift */, 63CF6D79203CC66000EC8927 /* ErrorTests.swift */, 635D64151D59635300BC0AF5 /* WhenTests.swift */, 635D64131D59635300BC0AF5 /* WhenConcurrentTests.swift */, 635D64111D59635300BC0AF5 /* WhenResolvedTests.swift */, 635D640E1D59635300BC0AF5 /* AfterTests.swift */, 0C42F3191FCF86240051309C /* HangTests.swift */, 635D64121D59635300BC0AF5 /* RaceTests.swift */, 635D641B1D59635300BC0AF5 /* DefaultDispatchQueueTests.swift */, 635D64171D59635300BC0AF5 /* RegressionTests.swift */, 635D64161D59635300BC0AF5 /* StressTests.swift */, 635D640D1D59635300BC0AF5 /* ZalgoTests.swift */, 639BF755203DF02C00FA577B /* Utilities.swift */, 085B96B121A6358900E5E22F /* LoggingTests.swift */, ); name = Core; path = Tests/CorePromise; sourceTree = ""; }; 631751AA1D59768200A9DDDC /* A+ */ = { isa = PBXGroup; children = ( 631751AB1D59768200A9DDDC /* 0.0.0.swift */, 631751AC1D59768200A9DDDC /* 2.1.2.swift */, 631751AD1D59768200A9DDDC /* 2.1.3.swift */, 631751AE1D59768200A9DDDC /* 2.2.2.swift */, 631751AF1D59768200A9DDDC /* 2.2.3.swift */, 631751B01D59768200A9DDDC /* 2.2.4.swift */, 631751B11D59768200A9DDDC /* 2.2.6.swift */, 631751B21D59768200A9DDDC /* 2.2.7.swift */, 631751B31D59768200A9DDDC /* 2.3.1.swift */, 631751B41D59768200A9DDDC /* 2.3.2.swift */, 631751B51D59768200A9DDDC /* 2.3.4.swift */, 631751B61D59768200A9DDDC /* README.md */, ); name = "A+"; path = "Tests/A+"; sourceTree = ""; }; 635893991D5BE51700F14B55 /* … */ = { isa = PBXGroup; children = ( 63B0AC581D595E1B00FA21D9 /* Products */, 63B0AC6C1D595E6300FA21D9 /* Info.plist */, 635893941D5BE4F900F14B55 /* LICENSE */, 635893951D5BE4F900F14B55 /* Package.swift */, 1F1DCDF72A27AB6400E7A16B /* PromiseKit.podspec */, ); name = "…"; sourceTree = ""; }; 635D64061D59630200BC0AF5 /* Tests */ = { isa = PBXGroup; children = ( C0244E6B2047ACAF00ACB4AC /* JS/A+ */, 631751AA1D59768200A9DDDC /* A+ */, 6314113D1D59797100E24B9E /* Bridging */, 6317518A1D59765700A9DDDC /* Core */, 630A8050203CEF6800D25F23 /* CoreObjC */, 63648C94203CB97400EBA011 /* DeprecationTests.swift */, ); name = Tests; sourceTree = ""; }; 6399A3711D595D9100D65233 = { isa = PBXGroup; children = ( 635893971D5BE4F900F14B55 /* README.md */, 635893921D5BE4E000F14B55 /* PromiseKit.playground */, 63B0AC761D595E6300FA21D9 /* PromiseKit.h */, 63B0AC601D595E4C00FA21D9 /* Sources.swift */, 63B912AB1F1E657400D49110 /* Sources.objc */, 635D64061D59630200BC0AF5 /* Tests */, 635893991D5BE51700F14B55 /* … */, ); sourceTree = ""; }; 63B0AC581D595E1B00FA21D9 /* Products */ = { isa = PBXGroup; children = ( 63B0AC571D595E1B00FA21D9 /* PromiseKit.framework */, 630019221D596292003B4E30 /* PMKCoreTests.xctest */, 631751A81D59766500A9DDDC /* PMKA+Tests.xctest */, 6314113C1D59795700E24B9E /* PMKBridgeTests.xctest */, 633027EA203CC0060037E136 /* PMKDeprecatedTests.xctest */, C0244E622047A6CB00ACB4AC /* PMKJSA+Tests.xctest */, ); name = Products; sourceTree = ""; }; 63B0AC601D595E4C00FA21D9 /* Sources.swift */ = { isa = PBXGroup; children = ( 9E4170F8287D88C800A3B4B5 /* Async.swift */, 9EC774262991495C00803027 /* Combine.swift */, 636A29191F1C156B001229C2 /* Promise.swift */, 636A29221F1C17A6001229C2 /* Guarantee.swift */, 636A29201F1C1716001229C2 /* Thenable.swift */, 632FBBE21F33B273008F8FBB /* Catchable.swift */, 63B912AC1F1E663E00D49110 /* Features */, 63B0AC691D595E6300FA21D9 /* Error.swift */, 636A29261F1C3927001229C2 /* Resolver.swift */, 636A291E1F1C16FF001229C2 /* Box.swift */, 6330B5E01F2E991200D60528 /* Configuration.swift */, 63B18AEB1F2D205C00B79E37 /* CustomStringConvertible.swift */, 63D9B2F020338D5D0075C00B /* Deprecations.swift */, 085B96BE21A9B37C00E5E22F /* LogEvent.swift */, 9E8028F82BDCEDBC0081E2D1 /* Resources */, ); name = Sources.swift; sourceTree = ""; }; 63B0AC9D1D595E6E00FA21D9 /* Internal Utilities */ = { isa = PBXGroup; children = ( 63B0AC661D595E6300FA21D9 /* AnyPromise+Private.h */, 63B0AC6F1D595E6300FA21D9 /* NSMethodSignatureForBlock.m */, 63B0AC711D595E6300FA21D9 /* PMKCallVariadicBlock.m */, ); name = "Internal Utilities"; sourceTree = ""; }; 63B912AB1F1E657400D49110 /* Sources.objc */ = { isa = PBXGroup; children = ( 63B0AC641D595E6300FA21D9 /* AnyPromise.m */, 63B0AC651D595E6300FA21D9 /* AnyPromise.swift */, 63B0AC671D595E6300FA21D9 /* dispatch_promise.m */, 630B60C01F2F73B000A1AEFE /* Headers */, 630B60BF1F2F739E00A1AEFE /* Features */, 63B0AC9D1D595E6E00FA21D9 /* Internal Utilities */, ); name = Sources.objc; sourceTree = ""; }; 63B912AC1F1E663E00D49110 /* Features */ = { isa = PBXGroup; children = ( 0CC3AF2A1FCF84F7000E98C9 /* hang.swift */, 63B0AC621D595E6300FA21D9 /* after.swift */, 63B912A91F1D7B1300D49110 /* firstly.swift */, 636A29241F1C3089001229C2 /* race.swift */, 63B0AC7D1D595E6300FA21D9 /* when.swift */, ); name = Features; sourceTree = ""; }; 9E8028F82BDCEDBC0081E2D1 /* Resources */ = { isa = PBXGroup; children = ( 9E8028F72BDCEDBC0081E2D1 /* PrivacyInfo.xcprivacy */, ); name = Resources; path = Sources/Resources; sourceTree = ""; }; C0244E6B2047ACAF00ACB4AC /* JS/A+ */ = { isa = PBXGroup; children = ( C0244E682047AC9F00ACB4AC /* AllTests.swift */, C013F7372048E3B6006B57B1 /* MockNodeEnvironment.swift */, C013F7392049076A006B57B1 /* JSPromise.swift */, C013F73B20494291006B57B1 /* JSAdapter.swift */, C013F73F204E5063006B57B1 /* JSUtils.swift */, ); name = "JS/A+"; sourceTree = ""; }; /* End PBXGroup section */ /* Begin PBXHeadersBuildPhase section */ 63B0AC541D595E1B00FA21D9 /* Headers */ = { isa = PBXHeadersBuildPhase; buildActionMask = 2147483647; files = ( 63B0AC931D595E6300FA21D9 /* PromiseKit.h in Headers */, 634AAD2B1EAE517C00B17855 /* fwd.h in Headers */, 63B0AC811D595E6300FA21D9 /* AnyPromise.h in Headers */, 63B0AC841D595E6300FA21D9 /* AnyPromise+Private.h in Headers */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXHeadersBuildPhase section */ /* Begin PBXNativeTarget section */ 630019011D596292003B4E30 /* PMKCoreTests */ = { isa = PBXNativeTarget; buildConfigurationList = 6300191F1D596292003B4E30 /* Build configuration list for PBXNativeTarget "PMKCoreTests" */; buildPhases = ( 630019021D596292003B4E30 /* Sources */, 630019181D596292003B4E30 /* Frameworks */, ); buildRules = ( ); dependencies = ( 635D64051D5962F900BC0AF5 /* PBXTargetDependency */, ); name = PMKCoreTests; productName = PromiseKit; productReference = 630019221D596292003B4E30 /* PMKCoreTests.xctest */; productType = "com.apple.product-type.bundle.unit-test"; }; 631411321D59795700E24B9E /* PMKBridgeTests */ = { isa = PBXNativeTarget; buildConfigurationList = 631411391D59795700E24B9E /* Build configuration list for PBXNativeTarget "PMKBridgeTests" */; buildPhases = ( 631411351D59795700E24B9E /* Sources */, 631411371D59795700E24B9E /* Frameworks */, ); buildRules = ( ); dependencies = ( 631411331D59795700E24B9E /* PBXTargetDependency */, ); name = PMKBridgeTests; productName = PromiseKit; productReference = 6314113C1D59795700E24B9E /* PMKBridgeTests.xctest */; productType = "com.apple.product-type.bundle.unit-test"; }; 6317518B1D59766500A9DDDC /* PMKA+Tests */ = { isa = PBXNativeTarget; buildConfigurationList = 631751A51D59766500A9DDDC /* Build configuration list for PBXNativeTarget "PMKA+Tests" */; buildPhases = ( 6317518E1D59766500A9DDDC /* Sources */, 631751A31D59766500A9DDDC /* Frameworks */, ); buildRules = ( ); dependencies = ( 6317518C1D59766500A9DDDC /* PBXTargetDependency */, ); name = "PMKA+Tests"; productName = PromiseKit; productReference = 631751A81D59766500A9DDDC /* PMKA+Tests.xctest */; productType = "com.apple.product-type.bundle.unit-test"; }; 633027E0203CC0060037E136 /* PMKDeprecatedTests */ = { isa = PBXNativeTarget; buildConfigurationList = 633027E7203CC0060037E136 /* Build configuration list for PBXNativeTarget "PMKDeprecatedTests" */; buildPhases = ( 633027E3203CC0060037E136 /* Sources */, 633027E5203CC0060037E136 /* Frameworks */, ); buildRules = ( ); dependencies = ( 633027E1203CC0060037E136 /* PBXTargetDependency */, ); name = PMKDeprecatedTests; productName = PromiseKit; productReference = 633027EA203CC0060037E136 /* PMKDeprecatedTests.xctest */; productType = "com.apple.product-type.bundle.unit-test"; }; 63B0AC561D595E1B00FA21D9 /* PromiseKit */ = { isa = PBXNativeTarget; buildConfigurationList = 63B0AC5F1D595E1B00FA21D9 /* Build configuration list for PBXNativeTarget "PromiseKit" */; buildPhases = ( 63B0AC541D595E1B00FA21D9 /* Headers */, 63B0AC521D595E1B00FA21D9 /* Sources */, 63B0AC531D595E1B00FA21D9 /* Frameworks */, ); buildRules = ( ); dependencies = ( ); name = PromiseKit; productName = PromiseKit; productReference = 63B0AC571D595E1B00FA21D9 /* PromiseKit.framework */; productType = "com.apple.product-type.framework"; }; C0244E4E2047A6CB00ACB4AC /* PMKJSA+Tests */ = { isa = PBXNativeTarget; buildConfigurationList = C0244E5F2047A6CB00ACB4AC /* Build configuration list for PBXNativeTarget "PMKJSA+Tests" */; buildPhases = ( C0244E512047A6CB00ACB4AC /* Sources */, C0244E5D2047A6CB00ACB4AC /* Frameworks */, C0244E6E2047AF0B00ACB4AC /* CopyFiles */, ); buildRules = ( ); dependencies = ( C0244E4F2047A6CB00ACB4AC /* PBXTargetDependency */, ); name = "PMKJSA+Tests"; productName = PromiseKit; productReference = C0244E622047A6CB00ACB4AC /* PMKJSA+Tests.xctest */; productType = "com.apple.product-type.bundle.unit-test"; }; /* End PBXNativeTarget section */ /* Begin PBXProject section */ 6399A3721D595D9100D65233 /* Project object */ = { isa = PBXProject; attributes = { LastUpgradeCheck = 1250; TargetAttributes = { 630019011D596292003B4E30 = { LastSwiftMigration = 1100; }; 631411321D59795700E24B9E = { LastSwiftMigration = 1100; }; 6317518B1D59766500A9DDDC = { LastSwiftMigration = 1100; }; 633027E0203CC0060037E136 = { LastSwiftMigration = 1100; }; 63B0AC561D595E1B00FA21D9 = { CreatedOnToolsVersion = 8.0; LastSwiftMigration = 1100; ProvisioningStyle = Automatic; }; C0244E4E2047A6CB00ACB4AC = { LastSwiftMigration = 1100; }; }; }; buildConfigurationList = 6399A3751D595D9100D65233 /* Build configuration list for PBXProject "PromiseKit" */; compatibilityVersion = "Xcode 3.2"; developmentRegion = en; hasScannedForEncodings = 0; knownRegions = ( en, Base, ); mainGroup = 6399A3711D595D9100D65233; productRefGroup = 63B0AC581D595E1B00FA21D9 /* Products */; projectDirPath = ""; projectRoot = ""; targets = ( 63B0AC561D595E1B00FA21D9 /* PromiseKit */, 6317518B1D59766500A9DDDC /* PMKA+Tests */, 631411321D59795700E24B9E /* PMKBridgeTests */, 630019011D596292003B4E30 /* PMKCoreTests */, 633027E0203CC0060037E136 /* PMKDeprecatedTests */, C0244E4E2047A6CB00ACB4AC /* PMKJSA+Tests */, ); }; /* End PBXProject section */ /* Begin PBXSourcesBuildPhase section */ 630019021D596292003B4E30 /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( 0C42F31B1FCF86320051309C /* HangTests.swift in Sources */, 635D641E1D59635300BC0AF5 /* CancellableErrorTests.swift in Sources */, 630A8056203CEF6800D25F23 /* AnyPromiseTests.m in Sources */, 635D64221D59635300BC0AF5 /* ZalgoTests.swift in Sources */, 635D64271D59635300BC0AF5 /* RaceTests.swift in Sources */, 9EC7742A2991498200803027 /* CombineTests.swift in Sources */, 632FBBE51F33B338008F8FBB /* CatchableTests.swift in Sources */, 63CF6D80203CD19200EC8927 /* ThenableTests.swift in Sources */, 635D642B1D59635300BC0AF5 /* StressTests.swift in Sources */, 630A805A203CEF6800D25F23 /* WhenTests.m in Sources */, 630A805B203CF67800D25F23 /* DefaultDispatchQueueTests.swift in Sources */, 635D641D1D59635300BC0AF5 /* PromiseTests.swift in Sources */, 63CF6D7C203CCDAB00EC8927 /* GuaranteeTests.swift in Sources */, 9E66231626FE5A8C00FA25CB /* RaceTests.m in Sources */, 639BF757203DF03100FA577B /* Utilities.swift in Sources */, 9E4170FC287D8DF900A3B4B5 /* AsyncTests.swift in Sources */, 635D64261D59635300BC0AF5 /* WhenResolvedTests.swift in Sources */, 635D64231D59635300BC0AF5 /* AfterTests.swift in Sources */, 63CF6D7A203CC66000EC8927 /* ErrorTests.swift in Sources */, 49A5584D1DC5185900E4D01B /* ResolverTests.swift in Sources */, 630A8057203CEF6800D25F23 /* PMKManifoldTests.m in Sources */, 085B96B321A6359500E5E22F /* LoggingTests.swift in Sources */, 63B7C94B203E2B8200FBEC00 /* AnyPromiseTests.swift in Sources */, 630A8059203CEF6800D25F23 /* HangTests.m in Sources */, 635D642A1D59635300BC0AF5 /* WhenTests.swift in Sources */, 630A8058203CEF6800D25F23 /* JoinTests.m in Sources */, 635D64281D59635300BC0AF5 /* WhenConcurrentTests.swift in Sources */, 635D642C1D59635300BC0AF5 /* RegressionTests.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; 631411351D59795700E24B9E /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( 631411461D59797100E24B9E /* Infrastructure.swift in Sources */, 631411431D59797100E24B9E /* BridgingTests.m in Sources */, 631411441D59797100E24B9E /* BridgingTests.swift in Sources */, 631411451D59797100E24B9E /* Infrastructure.m in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; 6317518E1D59766500A9DDDC /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( 631751C11D59768200A9DDDC /* 2.3.4.swift in Sources */, 631751BA1D59768200A9DDDC /* 2.2.2.swift in Sources */, 631751BF1D59768200A9DDDC /* 2.3.1.swift in Sources */, 631751B91D59768200A9DDDC /* 2.1.3.swift in Sources */, 631751BD1D59768200A9DDDC /* 2.2.6.swift in Sources */, 631751B71D59768200A9DDDC /* 0.0.0.swift in Sources */, 631751C01D59768200A9DDDC /* 2.3.2.swift in Sources */, 631751B81D59768200A9DDDC /* 2.1.2.swift in Sources */, 631751BE1D59768200A9DDDC /* 2.2.7.swift in Sources */, 631751BC1D59768200A9DDDC /* 2.2.4.swift in Sources */, 631751BB1D59768200A9DDDC /* 2.2.3.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; 633027E3203CC0060037E136 /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( 63CF6D7E203CD12700EC8927 /* DeprecationTests.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; 63B0AC521D595E1B00FA21D9 /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( 636A29251F1C3089001229C2 /* race.swift in Sources */, 63B0AC9A1D595E6300FA21D9 /* when.swift in Sources */, 636A29271F1C3927001229C2 /* Resolver.swift in Sources */, 63B0AC991D595E6300FA21D9 /* when.m in Sources */, 63D9B2EF203385FD0075C00B /* race.m in Sources */, 63B0AC801D595E6300FA21D9 /* after.swift in Sources */, 63B18AEC1F2D205C00B79E37 /* CustomStringConvertible.swift in Sources */, 085B96BF21A9B37C00E5E22F /* LogEvent.swift in Sources */, 9E4170F9287D88C900A3B4B5 /* Async.swift in Sources */, 6330B5E11F2E991200D60528 /* Configuration.swift in Sources */, 63B912AA1F1D7B1300D49110 /* firstly.swift in Sources */, 636A29211F1C1716001229C2 /* Thenable.swift in Sources */, 632FBBE31F33B273008F8FBB /* Catchable.swift in Sources */, 63B0AC851D595E6300FA21D9 /* dispatch_promise.m in Sources */, 636A291F1F1C16FF001229C2 /* Box.swift in Sources */, 63B0AC821D595E6300FA21D9 /* AnyPromise.m in Sources */, 636A29231F1C17A6001229C2 /* Guarantee.swift in Sources */, 636A291A1F1C156B001229C2 /* Promise.swift in Sources */, 63B0AC8B1D595E6300FA21D9 /* join.m in Sources */, 63B0AC891D595E6300FA21D9 /* hang.m in Sources */, 63B0AC831D595E6300FA21D9 /* AnyPromise.swift in Sources */, 9EC774272991495C00803027 /* Combine.swift in Sources */, 63D9B2F120338D5D0075C00B /* Deprecations.swift in Sources */, 63B0AC871D595E6300FA21D9 /* Error.swift in Sources */, 0CC3AF2B1FCF84F7000E98C9 /* hang.swift in Sources */, 63B0AC7F1D595E6300FA21D9 /* after.m in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; C0244E512047A6CB00ACB4AC /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( C013F73C20494291006B57B1 /* JSAdapter.swift in Sources */, C0244E692047AC9F00ACB4AC /* AllTests.swift in Sources */, C013F740204E5064006B57B1 /* JSUtils.swift in Sources */, C013F73A2049076A006B57B1 /* JSPromise.swift in Sources */, C013F7382048E3B6006B57B1 /* MockNodeEnvironment.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXSourcesBuildPhase section */ /* Begin PBXTargetDependency section */ 631411331D59795700E24B9E /* PBXTargetDependency */ = { isa = PBXTargetDependency; target = 63B0AC561D595E1B00FA21D9 /* PromiseKit */; targetProxy = 631411341D59795700E24B9E /* PBXContainerItemProxy */; }; 6317518C1D59766500A9DDDC /* PBXTargetDependency */ = { isa = PBXTargetDependency; target = 63B0AC561D595E1B00FA21D9 /* PromiseKit */; targetProxy = 6317518D1D59766500A9DDDC /* PBXContainerItemProxy */; }; 633027E1203CC0060037E136 /* PBXTargetDependency */ = { isa = PBXTargetDependency; target = 63B0AC561D595E1B00FA21D9 /* PromiseKit */; targetProxy = 633027E2203CC0060037E136 /* PBXContainerItemProxy */; }; 635D64051D5962F900BC0AF5 /* PBXTargetDependency */ = { isa = PBXTargetDependency; target = 63B0AC561D595E1B00FA21D9 /* PromiseKit */; targetProxy = 635D64041D5962F900BC0AF5 /* PBXContainerItemProxy */; }; C0244E4F2047A6CB00ACB4AC /* PBXTargetDependency */ = { isa = PBXTargetDependency; target = 63B0AC561D595E1B00FA21D9 /* PromiseKit */; targetProxy = C0244E502047A6CB00ACB4AC /* PBXContainerItemProxy */; }; /* End PBXTargetDependency section */ /* Begin XCBuildConfiguration section */ 630019201D596292003B4E30 /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; "LD_RUNPATH_SEARCH_PATHS[sdk=macosx*]" = "$(inherited) @executable_path/../Frameworks @loader_path/../Frameworks"; SWIFT_INSTALL_OBJC_HEADER = NO; }; name = Debug; }; 630019211D596292003B4E30 /* Release */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; "LD_RUNPATH_SEARCH_PATHS[sdk=macosx*]" = "$(inherited) @executable_path/../Frameworks @loader_path/../Frameworks"; SWIFT_INSTALL_OBJC_HEADER = NO; }; name = Release; }; 6314113A1D59795700E24B9E /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; "LD_RUNPATH_SEARCH_PATHS[sdk=macosx*]" = "$(inherited) @executable_path/../Frameworks @loader_path/../Frameworks"; SWIFT_INSTALL_OBJC_HEADER = NO; SWIFT_OBJC_BRIDGING_HEADER = Tests/Bridging/Infrastructure.h; }; name = Debug; }; 6314113B1D59795700E24B9E /* Release */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; "LD_RUNPATH_SEARCH_PATHS[sdk=macosx*]" = "$(inherited) @executable_path/../Frameworks @loader_path/../Frameworks"; SWIFT_INSTALL_OBJC_HEADER = NO; SWIFT_OBJC_BRIDGING_HEADER = Tests/Bridging/Infrastructure.h; }; name = Release; }; 631751A61D59766500A9DDDC /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; "LD_RUNPATH_SEARCH_PATHS[sdk=macosx*]" = "$(inherited) @executable_path/../Frameworks @loader_path/../Frameworks"; SWIFT_INSTALL_OBJC_HEADER = NO; }; name = Debug; }; 631751A71D59766500A9DDDC /* Release */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES; LD_RUNPATH_SEARCH_PATHS = "@executable_path/Frameworks @loader_path/Frameworks"; "LD_RUNPATH_SEARCH_PATHS[sdk=macosx*]" = "$(inherited) @executable_path/../Frameworks @loader_path/../Frameworks"; SWIFT_INSTALL_OBJC_HEADER = NO; }; name = Release; }; 633027E8203CC0060037E136 /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; "LD_RUNPATH_SEARCH_PATHS[sdk=macosx*]" = "$(inherited) @executable_path/../Frameworks @loader_path/../Frameworks"; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_INSTALL_OBJC_HEADER = NO; SWIFT_SUPPRESS_WARNINGS = YES; }; name = Debug; }; 633027E9203CC0060037E136 /* Release */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; "LD_RUNPATH_SEARCH_PATHS[sdk=macosx*]" = "$(inherited) @executable_path/../Frameworks @loader_path/../Frameworks"; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_INSTALL_OBJC_HEADER = NO; SWIFT_SUPPRESS_WARNINGS = YES; }; name = Release; }; 6399A3761D595D9100D65233 /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES; CLANG_ANALYZER_NONNULL = YES; CLANG_ENABLE_MODULES = YES; CLANG_ENABLE_OBJC_ARC = YES; CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; CLANG_WARN_BOOL_CONVERSION = YES; CLANG_WARN_COMMA = YES; CLANG_WARN_CONSTANT_CONVERSION = YES; CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; CLANG_WARN_INFINITE_RECURSION = YES; CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; CLANG_WARN_STRICT_PROTOTYPES = YES; CLANG_WARN_SUSPICIOUS_MOVE = YES; CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; COPY_PHASE_STRIP = NO; CURRENT_PROJECT_VERSION = 8.2.0; DEBUG_INFORMATION_FORMAT = dwarf; DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; ENABLE_STRICT_OBJC_MSGSEND = YES; ENABLE_TESTABILITY = YES; GCC_NO_COMMON_BLOCKS = YES; GCC_OPTIMIZATION_LEVEL = 0; GCC_PREPROCESSOR_DEFINITIONS = "DEBUG=1"; GCC_WARN_64_TO_32_BIT_CONVERSION = YES; GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_UNDECLARED_SELECTOR = YES; GCC_WARN_UNINITIALIZED_AUTOS = YES; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; INFOPLIST_FILE = "$(SRCROOT)/Sources/Info.plist"; IPHONEOS_DEPLOYMENT_TARGET = 11.0; LD_DYLIB_INSTALL_NAME = "@rpath"; MACOSX_DEPLOYMENT_TARGET = 10.13; ONLY_ACTIVE_ARCH = YES; PRODUCT_BUNDLE_IDENTIFIER = org.promisekit; PRODUCT_BUNDLE_PACKAGE_TYPE = BNDL; PRODUCT_NAME = "$(TARGET_NAME)"; SUPPORTED_PLATFORMS = "macosx appletvsimulator appletvos watchsimulator iphonesimulator watchos iphoneos"; SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; SWIFT_VERSION = 4.0; TVOS_DEPLOYMENT_TARGET = 11.0; VERSIONING_SYSTEM = "apple-generic"; WATCHOS_DEPLOYMENT_TARGET = 4.0; XROS_DEPLOYMENT_TARGET = 1.0; }; name = Debug; }; 6399A3771D595D9100D65233 /* Release */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES; CLANG_ANALYZER_NONNULL = YES; CLANG_ENABLE_MODULES = YES; CLANG_ENABLE_OBJC_ARC = YES; CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; CLANG_WARN_BOOL_CONVERSION = YES; CLANG_WARN_COMMA = YES; CLANG_WARN_CONSTANT_CONVERSION = YES; CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; CLANG_WARN_INFINITE_RECURSION = YES; CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; CLANG_WARN_STRICT_PROTOTYPES = YES; CLANG_WARN_SUSPICIOUS_MOVE = YES; CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; COPY_PHASE_STRIP = NO; CURRENT_PROJECT_VERSION = 8.2.0; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; ENABLE_NS_ASSERTIONS = NO; ENABLE_STRICT_OBJC_MSGSEND = YES; GCC_NO_COMMON_BLOCKS = YES; GCC_WARN_64_TO_32_BIT_CONVERSION = YES; GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_UNDECLARED_SELECTOR = YES; GCC_WARN_UNINITIALIZED_AUTOS = YES; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; INFOPLIST_FILE = "$(SRCROOT)/Sources/Info.plist"; IPHONEOS_DEPLOYMENT_TARGET = 11.0; LD_DYLIB_INSTALL_NAME = "@rpath"; MACOSX_DEPLOYMENT_TARGET = 10.13; PRODUCT_BUNDLE_IDENTIFIER = org.promisekit; PRODUCT_BUNDLE_PACKAGE_TYPE = BNDL; PRODUCT_NAME = "$(TARGET_NAME)"; SUPPORTED_PLATFORMS = "macosx appletvsimulator appletvos watchsimulator iphonesimulator watchos iphoneos"; SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; SWIFT_VERSION = 4.0; TVOS_DEPLOYMENT_TARGET = 11.0; VERSIONING_SYSTEM = "apple-generic"; WATCHOS_DEPLOYMENT_TARGET = 4.0; XROS_DEPLOYMENT_TARGET = 1.0; }; name = Release; }; 63B0AC5D1D595E1B00FA21D9 /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { APPLICATION_EXTENSION_API_ONLY = YES; CLANG_WARN_ASSIGN_ENUM = YES; CLANG_WARN_BOOL_CONVERSION = YES; CLANG_WARN_CONSTANT_CONVERSION = YES; CLANG_WARN_CXX0X_EXTENSIONS = YES; CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; CLANG_WARN_DOCUMENTATION_COMMENTS = YES; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; CLANG_WARN_IMPLICIT_SIGN_CONVERSION = YES; CLANG_WARN_INFINITE_RECURSION = YES; CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN_OBJC_EXPLICIT_OWNERSHIP_TYPE = YES; CLANG_WARN_OBJC_IMPLICIT_ATOMIC_PROPERTIES = YES; CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; CLANG_WARN_OBJC_MISSING_PROPERTY_SYNTHESIS = YES; CLANG_WARN_OBJC_REPEATED_USE_OF_WEAK = YES; CLANG_WARN_SUSPICIOUS_IMPLICIT_CONVERSION = YES; CLANG_WARN_UNREACHABLE_CODE = YES_AGGRESSIVE; CLANG_WARN__EXIT_TIME_DESTRUCTORS = YES; DEFINES_MODULE = YES; DYLIB_INSTALL_NAME_BASE = "@rpath"; ENABLE_TESTABILITY = YES; GCC_TREAT_IMPLICIT_FUNCTION_DECLARATIONS_AS_ERRORS = YES; GCC_TREAT_INCOMPATIBLE_POINTER_TYPE_WARNINGS_AS_ERRORS = YES; GCC_TREAT_WARNINGS_AS_ERRORS = NO; GCC_WARN_64_TO_32_BIT_CONVERSION = YES; GCC_WARN_ABOUT_MISSING_FIELD_INITIALIZERS = YES; GCC_WARN_ABOUT_MISSING_NEWLINE = YES; GCC_WARN_ABOUT_MISSING_PROTOTYPES = YES; GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_FOUR_CHARACTER_CONSTANTS = YES; GCC_WARN_HIDDEN_VIRTUAL_FUNCTIONS = YES; GCC_WARN_INITIALIZER_NOT_FULLY_BRACKETED = YES; GCC_WARN_NON_VIRTUAL_DESTRUCTOR = YES; GCC_WARN_SIGN_COMPARE = YES; GCC_WARN_STRICT_SELECTOR_MATCH = YES; GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNKNOWN_PRAGMAS = YES; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_LABEL = YES; GCC_WARN_UNUSED_PARAMETER = YES; GCC_WARN_UNUSED_VARIABLE = YES; LD_DYLIB_INSTALL_NAME = "$(DYLIB_INSTALL_NAME_BASE:standardizepath)/$(EXECUTABLE_PATH)"; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; PRODUCT_BUNDLE_PACKAGE_TYPE = FMWK; SKIP_INSTALL = YES; SUPPORTED_PLATFORMS = "$(AVAILABLE_PLATFORMS)"; SUPPORTS_MACCATALYST = YES; SUPPORTS_MAC_DESIGNED_FOR_IPHONE_IPAD = YES; SWIFT_TREAT_WARNINGS_AS_ERRORS = NO; TARGETED_DEVICE_FAMILY = "1,2,3,4,6,7"; }; name = Debug; }; 63B0AC5E1D595E1B00FA21D9 /* Release */ = { isa = XCBuildConfiguration; buildSettings = { APPLICATION_EXTENSION_API_ONLY = YES; BITCODE_GENERATION_MODE = bitcode; CLANG_WARN_ASSIGN_ENUM = YES; CLANG_WARN_BOOL_CONVERSION = YES; CLANG_WARN_CONSTANT_CONVERSION = YES; CLANG_WARN_CXX0X_EXTENSIONS = YES; CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; CLANG_WARN_DOCUMENTATION_COMMENTS = YES; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; CLANG_WARN_IMPLICIT_SIGN_CONVERSION = YES; CLANG_WARN_INFINITE_RECURSION = YES; CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN_OBJC_EXPLICIT_OWNERSHIP_TYPE = YES; CLANG_WARN_OBJC_IMPLICIT_ATOMIC_PROPERTIES = YES; CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; CLANG_WARN_OBJC_MISSING_PROPERTY_SYNTHESIS = YES; CLANG_WARN_OBJC_REPEATED_USE_OF_WEAK = YES; CLANG_WARN_SUSPICIOUS_IMPLICIT_CONVERSION = YES; CLANG_WARN_UNREACHABLE_CODE = YES_AGGRESSIVE; CLANG_WARN__EXIT_TIME_DESTRUCTORS = YES; DEFINES_MODULE = YES; DYLIB_INSTALL_NAME_BASE = "@rpath"; GCC_TREAT_IMPLICIT_FUNCTION_DECLARATIONS_AS_ERRORS = YES; GCC_TREAT_INCOMPATIBLE_POINTER_TYPE_WARNINGS_AS_ERRORS = YES; GCC_TREAT_WARNINGS_AS_ERRORS = NO; GCC_WARN_64_TO_32_BIT_CONVERSION = YES; GCC_WARN_ABOUT_MISSING_FIELD_INITIALIZERS = YES; GCC_WARN_ABOUT_MISSING_NEWLINE = YES; GCC_WARN_ABOUT_MISSING_PROTOTYPES = YES; GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_FOUR_CHARACTER_CONSTANTS = YES; GCC_WARN_HIDDEN_VIRTUAL_FUNCTIONS = YES; GCC_WARN_INITIALIZER_NOT_FULLY_BRACKETED = YES; GCC_WARN_NON_VIRTUAL_DESTRUCTOR = YES; GCC_WARN_SIGN_COMPARE = YES; GCC_WARN_STRICT_SELECTOR_MATCH = YES; GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNKNOWN_PRAGMAS = YES; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_LABEL = YES; GCC_WARN_UNUSED_PARAMETER = YES; GCC_WARN_UNUSED_VARIABLE = YES; LD_DYLIB_INSTALL_NAME = "$(DYLIB_INSTALL_NAME_BASE:standardizepath)/$(EXECUTABLE_PATH)"; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; PRODUCT_BUNDLE_PACKAGE_TYPE = FMWK; SKIP_INSTALL = YES; SUPPORTED_PLATFORMS = "$(AVAILABLE_PLATFORMS)"; SUPPORTS_MACCATALYST = YES; SUPPORTS_MAC_DESIGNED_FOR_IPHONE_IPAD = YES; SWIFT_TREAT_WARNINGS_AS_ERRORS = NO; TARGETED_DEVICE_FAMILY = "1,2,3,4,6,7"; }; name = Release; }; C0244E602047A6CB00ACB4AC /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES; CLANG_ENABLE_MODULES = YES; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; "LD_RUNPATH_SEARCH_PATHS[sdk=macosx*]" = "$(inherited) @executable_path/../Frameworks @loader_path/../Frameworks"; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_INSTALL_OBJC_HEADER = NO; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; }; name = Debug; }; C0244E612047A6CB00ACB4AC /* Release */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES; CLANG_ENABLE_MODULES = YES; LD_RUNPATH_SEARCH_PATHS = "@executable_path/Frameworks @loader_path/Frameworks"; "LD_RUNPATH_SEARCH_PATHS[sdk=macosx*]" = "$(inherited) @executable_path/../Frameworks @loader_path/../Frameworks"; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_INSTALL_OBJC_HEADER = NO; }; name = Release; }; /* End XCBuildConfiguration section */ /* Begin XCConfigurationList section */ 6300191F1D596292003B4E30 /* Build configuration list for PBXNativeTarget "PMKCoreTests" */ = { isa = XCConfigurationList; buildConfigurations = ( 630019201D596292003B4E30 /* Debug */, 630019211D596292003B4E30 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; 631411391D59795700E24B9E /* Build configuration list for PBXNativeTarget "PMKBridgeTests" */ = { isa = XCConfigurationList; buildConfigurations = ( 6314113A1D59795700E24B9E /* Debug */, 6314113B1D59795700E24B9E /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; 631751A51D59766500A9DDDC /* Build configuration list for PBXNativeTarget "PMKA+Tests" */ = { isa = XCConfigurationList; buildConfigurations = ( 631751A61D59766500A9DDDC /* Debug */, 631751A71D59766500A9DDDC /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; 633027E7203CC0060037E136 /* Build configuration list for PBXNativeTarget "PMKDeprecatedTests" */ = { isa = XCConfigurationList; buildConfigurations = ( 633027E8203CC0060037E136 /* Debug */, 633027E9203CC0060037E136 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; 6399A3751D595D9100D65233 /* Build configuration list for PBXProject "PromiseKit" */ = { isa = XCConfigurationList; buildConfigurations = ( 6399A3761D595D9100D65233 /* Debug */, 6399A3771D595D9100D65233 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; 63B0AC5F1D595E1B00FA21D9 /* Build configuration list for PBXNativeTarget "PromiseKit" */ = { isa = XCConfigurationList; buildConfigurations = ( 63B0AC5D1D595E1B00FA21D9 /* Debug */, 63B0AC5E1D595E1B00FA21D9 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; C0244E5F2047A6CB00ACB4AC /* Build configuration list for PBXNativeTarget "PMKJSA+Tests" */ = { isa = XCConfigurationList; buildConfigurations = ( C0244E602047A6CB00ACB4AC /* Debug */, C0244E612047A6CB00ACB4AC /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; /* End XCConfigurationList section */ }; rootObject = 6399A3721D595D9100D65233 /* Project object */; } ================================================ FILE: PromiseKit.xcodeproj/project.xcworkspace/contents.xcworkspacedata ================================================ ================================================ FILE: PromiseKit.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist ================================================ IDEDidComputeMac32BitWarning ================================================ FILE: PromiseKit.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings ================================================ IDEWorkspaceSharedSettings_AutocreateContextsIfNeeded ================================================ FILE: PromiseKit.xcodeproj/xcshareddata/xcschemes/PromiseKit.xcscheme ================================================ ================================================ FILE: README.md ================================================ ![PromiseKit](../gh-pages/public/img/logo-tight.png) [![badge-pod][]][cocoapods] ![badge-languages][] ![badge-pms][] ![badge-platforms][] [![codecov](https://codecov.io/gh/mxcl/PromiseKit/branch/master/graph/badge.svg?token=wHSAz7N8WA)](https://codecov.io/gh/mxcl/PromiseKit) --- Promises simplify asynchronous programming, freeing you up to focus on the more important things. They are easy to learn, easy to master and result in clearer, more readable code. Your co-workers will thank you. ```swift UIApplication.shared.isNetworkActivityIndicatorVisible = true let fetchImage = URLSession.shared.dataTask(.promise, with: url).compactMap{ UIImage(data: $0.data) } let fetchLocation = CLLocationManager.requestLocation().lastValue firstly { when(fulfilled: fetchImage, fetchLocation) }.done { image, location in self.imageView.image = image self.label.text = "\(location)" }.ensure { UIApplication.shared.isNetworkActivityIndicatorVisible = false }.catch { error in self.show(UIAlertController(for: error), sender: self) } ``` PromiseKit is a thoughtful and complete implementation of promises for any platform that has a `swiftc`. It has *excellent* Objective-C bridging and *delightful* specializations for iOS, macOS, tvOS and watchOS. It is a top-100 pod used in many of the most popular apps in the world. [![codecov](https://codecov.io/gh/mxcl/PromiseKit/branch/master/graph/badge.svg)](https://codecov.io/gh/mxcl/PromiseKit) # Quick Start In your [Podfile]: ```ruby use_frameworks! target "Change Me!" do pod "PromiseKit", "~> 8" end ``` PromiseKit 8 supports recent Xcodes (13+). Some Podspecs were [dropped as a result](https://github.com/mxcl/PromiseKit/pull/1318). Pull requests are welcome. PromiseKit 6, 5 and 4 support Xcode 8.3, 9.x and 10.0; Swift 3.1, 3.2, 3.3, 3.4, 4.0, 4.1, 4.2, 4.3 and 5.0 (development snapshots); iOS, macOS, tvOS, watchOS, Linux and Android; CocoaPods, Carthage and SwiftPM; ([CI Matrix](https://travis-ci.org/mxcl/PromiseKit)). For Carthage, SwiftPM, Accio, etc., or for instructions when using older Swifts or Xcodes, see our [Installation Guide]. We recommend [Carthage](https://github.com/Carthage/Carthage) or [Accio](https://github.com/JamitLabs/Accio). # PromiseKit and Swift 5.5+ Async/Await As of Swift 5.5, the Swift language now offers support for [built-in concurrency with async / await](https://docs.swift.org/swift-book/LanguageGuide/Concurrency.html). See [Async+](https://github.com/async-plus/async-plus) for a port of PromiseKit's most useful patterns to this new paradigm. # Professionally Supported PromiseKit is Now Available TideLift gives software development teams a single source for purchasing and maintaining their software, with professional grade assurances from the experts who know it best, while seamlessly integrating with existing tools. [Get Professional Support for PromiseKit with TideLift](https://tidelift.com/subscription/pkg/cocoapods-promisekit?utm_source=cocoapods-promisekit&utm_medium=referral&utm_campaign=readme). # Documentation * Handbook * [Getting Started](Documentation/GettingStarted.md) * [Promises: Common Patterns](Documentation/CommonPatterns.md) * [Frequently Asked Questions](Documentation/FAQ.md) * Manual * [Installation Guide](Documentation/Installation.md) * [Objective-C Guide](Documentation/ObjectiveC.md) * [Troubleshooting](Documentation/Troubleshooting.md) (e.g., solutions to common compile errors) * [Appendix](Documentation/Appendix.md) * [API Reference](https://mxcl.dev/PromiseKit/reference/v6/Classes/Promise.html) # Extensions Promises are only as useful as the asynchronous tasks they represent. Thus, we have converted (almost) all of Apple’s APIs to promises. The default CocoaPod provides Promises and the extensions for Foundation and UIKit. The other extensions are available by specifying additional subspecs in your `Podfile`, e.g.: ```ruby pod "PromiseKit/MapKit" # MKDirections().calculate().then { /*…*/ } pod "PromiseKit/CoreLocation" # CLLocationManager.requestLocation().then { /*…*/ } ``` All our extensions are separate repositories at the [PromiseKit organization]. ## I don't want the extensions! Then don’t have them: ```ruby pod "PromiseKit/CorePromise", "~> 8" ``` > *Note:* Carthage installations come with no extensions by default. ## Networking Promise chains commonly start with a network operation. Thus, we offer extensions for `URLSession`: ```swift // pod 'PromiseKit/Foundation' # https://github.com/PromiseKit/Foundation firstly { URLSession.shared.dataTask(.promise, with: try makeUrlRequest()).validate() // ^^ we provide `.validate()` so that eg. 404s get converted to errors }.map { try JSONDecoder().decode(Foo.self, with: $0.data) }.done { foo in //… }.catch { error in //… } func makeUrlRequest() throws -> URLRequest { var rq = URLRequest(url: url) rq.httpMethod = "POST" rq.addValue("application/json", forHTTPHeaderField: "Content-Type") rq.addValue("application/json", forHTTPHeaderField: "Accept") rq.httpBody = try JSONEncoder().encode(obj) return rq } ``` Support for Alamofire is welcome, please submit a PR. # Support Please check our [Troubleshooting Guide](Documentation/Troubleshooting.md), and if after that you still have a question, ask at our [Gitter chat channel] or on [our bug tracker]. ## Security & Vulnerability Reporting or Disclosure https://tidelift.com/security [badge-pod]: https://img.shields.io/cocoapods/v/PromiseKit.svg?label=version [badge-pms]: https://img.shields.io/badge/supports-CocoaPods%20%7C%20Carthage%20%7C%20Accio%20%7C%20SwiftPM-green.svg [badge-languages]: https://img.shields.io/badge/languages-Swift%20%7C%20ObjC-orange.svg [badge-platforms]: https://img.shields.io/badge/platforms-macOS%20%7C%20iOS%20%7C%20watchOS%20%7C%20tvOS%20%7C%20Linux-lightgrey.svg [badge-mit]: https://img.shields.io/badge/license-MIT-blue.svg [OMGHTTPURLRQ]: https://github.com/PromiseKit/OMGHTTPURLRQ [Alamofire]: http://github.com/PromiseKit/Alamofire- [PromiseKit organization]: https://github.com/PromiseKit [Gitter chat channel]: https://gitter.im/mxcl/PromiseKit [our bug tracker]: https://github.com/mxcl/PromiseKit/issues/new [Podfile]: https://guides.cocoapods.org/syntax/podfile.html [PMK6]: http://mxcl.dev/PromiseKit/news/2018/02/PromiseKit-6.0-Released/ [Installation Guide]: Documentation/Installation.md [badge-travis]: https://travis-ci.org/mxcl/PromiseKit.svg?branch=master [travis]: https://travis-ci.org/mxcl/PromiseKit [cocoapods]: https://cocoapods.org/pods/PromiseKit ================================================ FILE: Sources/AnyPromise+Private.h ================================================ @import Foundation.NSError; @import Foundation.NSPointerArray; #if TARGET_OS_IPHONE #define NSPointerArrayMake(N) ({ \ NSPointerArray *aa = [NSPointerArray strongObjectsPointerArray]; \ aa.count = N; \ aa; \ }) #else static inline NSPointerArray * __nonnull NSPointerArrayMake(NSUInteger count) { #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" NSPointerArray *aa = [[NSPointerArray class] respondsToSelector:@selector(strongObjectsPointerArray)] ? [NSPointerArray strongObjectsPointerArray] : [NSPointerArray pointerArrayWithStrongObjects]; #pragma clang diagnostic pop aa.count = count; return aa; } #endif #define IsError(o) [o isKindOfClass:[NSError class]] #define IsPromise(o) [o isKindOfClass:[AnyPromise class]] #import "AnyPromise.h" @class PMKArray; @interface AnyPromise () - (void)__pipe:(void(^ __nonnull)(__nullable id))block NS_REFINED_FOR_SWIFT; @end ================================================ FILE: Sources/AnyPromise.h ================================================ #import #import #import /// INTERNAL DO NOT USE @class __AnyPromise; /// Provided to simplify some usage sites typedef void (^PMKResolver)(id __nullable) NS_REFINED_FOR_SWIFT; /// An Objective-C implementation of the promise pattern. @interface AnyPromise: NSObject /** Create a new promise that resolves with the provided block. Use this method when wrapping asynchronous code that does *not* use promises so that this code can be used in promise chains. If `resolve` is called with an `NSError` object, the promise is rejected, otherwise the promise is fulfilled. Don’t use this method if you already have promises! Instead, just return your promise. Should you need to fulfill a promise but have no sensical value to use: your promise is a `void` promise: fulfill with `nil`. The block you pass is executed immediately on the calling thread. - Parameter block: The provided block is immediately executed, inside the block call `resolve` to resolve this promise and cause any attached handlers to execute. If you are wrapping a delegate-based system, we recommend instead to use: initWithResolver: - Returns: A new promise. - Warning: Resolving a promise with `nil` fulfills it. - SeeAlso: https://github.com/mxcl/PromiseKit/blob/master/Documentation/GettingStarted.md#making-promises - SeeAlso: https://github.com/mxcl/PromiseKit/blob/master/Documentation/CommonPatterns.md#wrapping-delegate-systems */ + (instancetype __nonnull)promiseWithResolverBlock:(void (^ __nonnull)(__nonnull PMKResolver))resolveBlock NS_REFINED_FOR_SWIFT; /// INTERNAL DO NOT USE - (instancetype __nonnull)initWith__D:(__AnyPromise * __nonnull)d; /** Creates a resolved promise. When developing your own promise systems, it is occasionally useful to be able to return an already resolved promise. - Parameter value: The value with which to resolve this promise. Passing an `NSError` will cause the promise to be rejected, passing an AnyPromise will return a new AnyPromise bound to that promise, otherwise the promise will be fulfilled with the value passed. - Returns: A resolved promise. */ + (instancetype __nonnull)promiseWithValue:(__nullable id)value NS_REFINED_FOR_SWIFT; /** The value of the asynchronous task this promise represents. A promise has `nil` value if the asynchronous task it represents has not finished. If the value is `nil` the promise is still `pending`. - Warning: *Note* Our Swift variant’s value property returns nil if the promise is rejected where AnyPromise will return the error object. This fits with the pattern where AnyPromise is not strictly typed and is more dynamic, but you should be aware of the distinction. - Note: If the AnyPromise was fulfilled with a `PMKManifold`, returns only the first fulfillment object. - Returns: The value with which this promise was resolved or `nil` if this promise is pending. */ @property (nonatomic, readonly) __nullable id value NS_REFINED_FOR_SWIFT; /// - Returns: if the promise is pending resolution. @property (nonatomic, readonly) BOOL pending NS_REFINED_FOR_SWIFT; /// - Returns: if the promise is resolved and fulfilled. @property (nonatomic, readonly) BOOL fulfilled NS_REFINED_FOR_SWIFT; /// - Returns: if the promise is resolved and rejected. @property (nonatomic, readonly) BOOL rejected NS_REFINED_FOR_SWIFT; /** The provided block is executed when its receiver is fulfilled. If you provide a block that takes a parameter, the value of the receiver will be passed as that parameter. [NSURLSession GET:url].then(^(NSData *data){ // do something with data }); @return A new promise that is resolved with the value returned from the provided block. For example: [NSURLSession GET:url].then(^(NSData *data){ return data.length; }).then(^(NSNumber *number){ //… }); @warning *Important* The block passed to `then` may take zero, one, two or three arguments, and return an object or return nothing. This flexibility is why the method signature for then is `id`, which means you will not get completion for the block parameter, and must type it yourself. It is safe to type any block syntax here, so to start with try just: `^{}`. @warning *Important* If an `NSError` or `NSString` is thrown inside your block, or you return an `NSError` object the next `Promise` will be rejected. See `catch` for documentation on error handling. @warning *Important* `then` is always executed on the main queue. @see thenOn @see thenInBackground */ - (AnyPromise * __nonnull (^ __nonnull)(id __nonnull))then NS_REFINED_FOR_SWIFT; /** The provided block is executed on the default queue when the receiver is fulfilled. This method is provided as a convenience for `thenOn`. @see then @see thenOn */ - (AnyPromise * __nonnull(^ __nonnull)(id __nonnull))thenInBackground NS_REFINED_FOR_SWIFT; /** The provided block is executed on the dispatch queue of your choice when the receiver is fulfilled. @see then @see thenInBackground */ - (AnyPromise * __nonnull(^ __nonnull)(dispatch_queue_t __nonnull, id __nonnull))thenOn NS_REFINED_FOR_SWIFT; #ifndef __cplusplus /** The provided block is executed when the receiver is rejected. Provide a block of form `^(NSError *){}` or simply `^{}`. The parameter has type `id` to give you the freedom to choose either. The provided block always runs on the main queue. @warning *Note* Cancellation errors are not caught. @warning *Note* Since catch is a c++ keyword, this method is not available in Objective-C++ files. Instead use catchOn. @see catchOn @see catchInBackground */ - (AnyPromise * __nonnull(^ __nonnull)(id __nonnull))catch NS_REFINED_FOR_SWIFT; #endif /** The provided block is executed when the receiver is rejected. Provide a block of form `^(NSError *){}` or simply `^{}`. The parameter has type `id` to give you the freedom to choose either. The provided block always runs on the global background queue. @warning *Note* Cancellation errors are not caught. @warning *Note* Since catch is a c++ keyword, this method is not available in Objective-C++ files. Instead use catchWithPolicy. @see catch @see catchOn */ - (AnyPromise * __nonnull(^ __nonnull)(id __nonnull))catchInBackground NS_REFINED_FOR_SWIFT; /** The provided block is executed when the receiver is rejected. Provide a block of form `^(NSError *){}` or simply `^{}`. The parameter has type `id` to give you the freedom to choose either. The provided block always runs on queue provided. @warning *Note* Cancellation errors are not caught. @see catch @see catchInBackground */ - (AnyPromise * __nonnull(^ __nonnull)(dispatch_queue_t __nonnull, id __nonnull))catchOn NS_REFINED_FOR_SWIFT; /** The provided block is executed when the receiver is resolved. The provided block always runs on the main queue. @see ensureOn */ - (AnyPromise * __nonnull(^ __nonnull)(dispatch_block_t __nonnull))ensure NS_REFINED_FOR_SWIFT; /** The provided block is executed on the dispatch queue of your choice when the receiver is resolved. @see ensure */ - (AnyPromise * __nonnull(^ __nonnull)(dispatch_queue_t __nonnull, dispatch_block_t __nonnull))ensureOn NS_REFINED_FOR_SWIFT; /** The provided block is executed on the global background queue when the receiver is resolved. @see ensure */ - (AnyPromise * __nonnull(^ __nonnull)(dispatch_block_t __nonnull))ensureInBackground 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. Use this method when wrapping asynchronous code that does *not* use promises so that this code can be used in promise chains. Generally, prefer `promiseWithResolverBlock:` as the resulting code is more elegant. PMKResolver resolve; AnyPromise *promise = [[AnyPromise alloc] initWithResolver:&resolve]; // later resolve(@"foo"); @param resolver A reference to a block pointer of PMKResolver type. You can then call your resolver to resolve this promise. @return A new promise. @warning *Important* The resolver strongly retains the promise. @see promiseWithResolverBlock: */ - (instancetype __nonnull)initWithResolver:(PMKResolver __strong __nonnull * __nonnull)resolver NS_REFINED_FOR_SWIFT; /** Unavailable methods */ - (instancetype __nonnull)init __attribute__((unavailable("It is illegal to create an unresolvable promise."))); + (instancetype __nonnull)new __attribute__((unavailable("It is illegal to create an unresolvable promise."))); - (AnyPromise * __nonnull(^ __nonnull)(dispatch_block_t __nonnull))always __attribute__((unavailable("See -ensure"))); - (AnyPromise * __nonnull(^ __nonnull)(dispatch_block_t __nonnull))alwaysOn __attribute__((unavailable("See -ensureOn"))); - (AnyPromise * __nonnull(^ __nonnull)(dispatch_block_t __nonnull))finally __attribute__((unavailable("See -ensure"))); - (AnyPromise * __nonnull(^ __nonnull)(dispatch_block_t __nonnull, dispatch_block_t __nonnull))finallyOn __attribute__((unavailable("See -ensureOn"))); @end typedef void (^PMKAdapter)(id __nullable, NSError * __nullable) NS_REFINED_FOR_SWIFT; typedef void (^PMKIntegerAdapter)(NSInteger, NSError * __nullable) NS_REFINED_FOR_SWIFT; typedef void (^PMKBooleanAdapter)(BOOL, NSError * __nullable) NS_REFINED_FOR_SWIFT; @interface AnyPromise (Adapters) /** Create a new promise by adapting an existing asynchronous system. The pattern of a completion block that passes two parameters, the first the result and the second an `NSError` object is so common that we provide this convenience adapter to make wrapping such systems more elegant. return [PMKPromise promiseWithAdapterBlock:^(PMKAdapter adapter){ PFQuery *query = [PFQuery …]; [query findObjectsInBackgroundWithBlock:adapter]; }]; @warning *Important* If both parameters are nil, the promise fulfills, if both are non-nil the promise rejects. This is per the convention. @see https://github.com/mxcl/PromiseKit/blob/master/Documentation/GettingStarted.md#making-promises */ + (instancetype __nonnull)promiseWithAdapterBlock:(void (^ __nonnull)(PMKAdapter __nonnull adapter))block NS_REFINED_FOR_SWIFT; /** Create a new promise by adapting an existing asynchronous system. Adapts asynchronous systems that complete with `^(NSInteger, NSError *)`. NSInteger will cast to enums provided the enum has been wrapped with `NS_ENUM`. All of Apple’s enums are, so if you find one that hasn’t you may need to make a pull-request. @see promiseWithAdapter */ + (instancetype __nonnull)promiseWithIntegerAdapterBlock:(void (^ __nonnull)(PMKIntegerAdapter __nonnull adapter))block NS_REFINED_FOR_SWIFT; /** Create a new promise by adapting an existing asynchronous system. Adapts asynchronous systems that complete with `^(BOOL, NSError *)`. @see promiseWithAdapter */ + (instancetype __nonnull)promiseWithBooleanAdapterBlock:(void (^ __nonnull)(PMKBooleanAdapter __nonnull adapter))block NS_REFINED_FOR_SWIFT; @end #ifdef __cplusplus extern "C" { #endif /** Whenever resolving a promise you may resolve with a tuple, eg. returning from a `then` or `catch` handler or resolving a new promise. Consumers of your Promise are not compelled to consume any arguments and in fact will often only consume the first parameter. Thus ensure the order of parameters is: from most-important to least-important. Currently PromiseKit limits you to THREE parameters to the manifold. */ #define PMKManifold(...) __PMKManifold(__VA_ARGS__, 3, 2, 1) #define __PMKManifold(_1, _2, _3, N, ...) __PMKArrayWithCount(N, _1, _2, _3) extern id __nonnull __PMKArrayWithCount(NSUInteger, ...); #ifdef __cplusplus } // Extern C #endif __attribute__((unavailable("See AnyPromise"))) @interface PMKPromise @end ================================================ FILE: Sources/AnyPromise.m ================================================ #if __has_include("PromiseKit-Swift.h") #import "PromiseKit-Swift.h" #else #import #endif #import "PMKCallVariadicBlock.m" #import "AnyPromise+Private.h" #import "AnyPromise.h" NSString *const PMKErrorDomain = @"PMKErrorDomain"; @implementation AnyPromise { __AnyPromise *d; } - (instancetype)initWith__D:(__AnyPromise *)dd { self = [super init]; if (self) self->d = dd; return self; } - (instancetype)initWithResolver:(PMKResolver __strong *)resolver { self = [super init]; if (self) d = [[__AnyPromise alloc] initWithResolver:^(void (^resolve)(id)) { *resolver = resolve; }]; return self; } + (instancetype)promiseWithResolverBlock:(void (^)(PMKResolver _Nonnull))resolveBlock { id d = [[__AnyPromise alloc] initWithResolver:resolveBlock]; return [[self alloc] initWith__D:d]; } + (instancetype)promiseWithValue:(id)value { //TODO provide a more efficient route for sealed promises id d = [[__AnyPromise alloc] initWithResolver:^(void (^resolve)(id)) { resolve(value); }]; return [[self alloc] initWith__D:d]; } //TODO remove if possible, but used by when.m - (void)__pipe:(void (^)(id _Nullable))block { [d __pipe:block]; } //NOTE used by AnyPromise.swift - (id)__d { return d; } - (AnyPromise *(^)(id))then { return ^(id block) { return [self->d __thenOn:dispatch_get_main_queue() execute:^(id obj) { return PMKCallVariadicBlock(block, obj); }]; }; } - (AnyPromise *(^)(dispatch_queue_t, id))thenOn { return ^(dispatch_queue_t queue, id block) { return [self->d __thenOn:queue execute:^(id obj) { return PMKCallVariadicBlock(block, obj); }]; }; } - (AnyPromise *(^)(id))thenInBackground { return ^(id block) { return [self->d __thenOn:dispatch_get_global_queue(0, 0) execute:^(id obj) { return PMKCallVariadicBlock(block, obj); }]; }; } - (AnyPromise *(^)(dispatch_queue_t, id))catchOn { return ^(dispatch_queue_t q, id block) { return [self->d __catchOn:q execute:^(id obj) { return PMKCallVariadicBlock(block, obj); }]; }; } - (AnyPromise *(^)(id))catch { return ^(id block) { return [self->d __catchOn:dispatch_get_main_queue() execute:^(id obj) { return PMKCallVariadicBlock(block, obj); }]; }; } - (AnyPromise *(^)(id))catchInBackground { return ^(id block) { return [self->d __catchOn:dispatch_get_global_queue(0, 0) execute:^(id obj) { return PMKCallVariadicBlock(block, obj); }]; }; } - (AnyPromise *(^)(dispatch_block_t))ensure { return ^(dispatch_block_t block) { return [self->d __ensureOn:dispatch_get_main_queue() execute:block]; }; } - (AnyPromise *(^)(dispatch_queue_t, dispatch_block_t))ensureOn { return ^(dispatch_queue_t queue, dispatch_block_t block) { return [self->d __ensureOn:queue execute:block]; }; } - (AnyPromise *(^)(dispatch_block_t))ensureInBackground { return ^(dispatch_block_t block) { return [self->d __ensureOn:dispatch_get_global_queue(QOS_CLASS_UNSPECIFIED, 0) execute:block]; }; } - (id)wait { return [d __wait]; } - (BOOL)pending { return [[d valueForKey:@"__pending"] boolValue]; } - (BOOL)rejected { return IsError([d __value]); } - (BOOL)fulfilled { return !self.rejected; } - (id)value { id obj = [d __value]; if ([obj isKindOfClass:[PMKArray class]]) { return obj[0]; } else { return obj; } } @end @implementation AnyPromise (Adapters) + (instancetype)promiseWithAdapterBlock:(void (^)(PMKAdapter))block { return [self promiseWithResolverBlock:^(PMKResolver resolve) { block(^(id value, id error){ resolve(error ?: value); }); }]; } + (instancetype)promiseWithIntegerAdapterBlock:(void (^)(PMKIntegerAdapter))block { return [self promiseWithResolverBlock:^(PMKResolver resolve) { block(^(NSInteger value, id error){ if (error) { resolve(error); } else { resolve(@(value)); } }); }]; } + (instancetype)promiseWithBooleanAdapterBlock:(void (^)(PMKBooleanAdapter adapter))block { return [self promiseWithResolverBlock:^(PMKResolver resolve) { block(^(BOOL value, id error){ if (error) { resolve(error); } else { resolve(@(value)); } }); }]; } @end ================================================ FILE: Sources/AnyPromise.swift ================================================ import Foundation /** __AnyPromise is an implementation detail. Because of how ObjC/Swift compatibility work we have to compose our AnyPromise with this internal object, however this is still part of the public interface. Sadly. Please don’t use it. */ @objc(__AnyPromise) public class __AnyPromise: NSObject { fileprivate let box: Box @objc public init(resolver body: (@escaping (Any?) -> Void) -> Void) { box = EmptyBox() super.init() body { if let p = $0 as? AnyPromise { p.d.__pipe(self.box.seal) } else { self.box.seal($0) } } } @objc public func __thenOn(_ q: DispatchQueue, execute: @escaping (Any?) -> Any?) -> AnyPromise { return AnyPromise(__D: __AnyPromise(resolver: { resolve in self.__pipe { obj in if !(obj is NSError) { q.async { resolve(execute(obj)) } } else { resolve(obj) } } })) } @objc public func __catchOn(_ q: DispatchQueue, execute: @escaping (Any?) -> Any?) -> AnyPromise { return AnyPromise(__D: __AnyPromise(resolver: { resolve in self.__pipe { obj in if obj is NSError { q.async { resolve(execute(obj)) } } else { resolve(obj) } } })) } @objc public func __ensureOn(_ q: DispatchQueue, execute: @escaping () -> Void) -> AnyPromise { return AnyPromise(__D: __AnyPromise(resolver: { resolve in self.__pipe { obj in q.async { execute() resolve(obj) } } })) } @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 if obj is NSError { to(obj) // or we cannot determine if objects are errors in objc land } else { to(obj) } } switch box.inspect() { case .pending: box.inspect { switch $0 { case .pending(let handlers): handlers.append { obj in to(obj) } case .resolved(let obj): to(obj) } } case .resolved(let obj): to(obj) } } @objc public var __value: Any? { switch box.inspect() { case .resolved(let obj): return obj default: return nil } } @objc public var __pending: Bool { switch box.inspect() { case .pending: return true case .resolved: return false } } } extension AnyPromise: Thenable, CatchMixin { /// - Returns: A new `AnyPromise` bound to a `Promise`. public convenience init(_ bridge: U) { self.init(__D: __AnyPromise(resolver: { resolve in bridge.pipe { switch $0 { case .rejected(let error): resolve(error as NSError) case .fulfilled(let value): resolve(value) } } })) } public func pipe(to body: @escaping (Result) -> Void) { func fulfill() { // calling through to the ObjC `value` property unwraps (any) PMKManifold // and considering this is the Swift pipe; we want that. body(.fulfilled(self.value(forKey: "value"))) } switch box.inspect() { case .pending: box.inspect { switch $0 { case .pending(let handlers): handlers.append { if let error = $0 as? Error { body(.rejected(error)) } else { fulfill() } } case .resolved(let error as Error): body(.rejected(error)) case .resolved: fulfill() } } case .resolved(let error as Error): body(.rejected(error)) case .resolved: fulfill() } } fileprivate var d: __AnyPromise { return value(forKey: "__d") as! __AnyPromise } var box: Box { return d.box } public var result: Result? { guard let value = __value else { return nil } if let error = value as? Error { return .rejected(error) } else { return .fulfilled(value) } } public typealias T = Any? } #if swift(>=3.1) public extension Promise where T == Any? { convenience init(_ anyPromise: AnyPromise) { self.init { anyPromise.pipe(to: $0.resolve) } } } #else extension AnyPromise { public func asPromise() -> Promise { return Promise(.pending, resolver: { resolve in pipe { result in switch result { case .rejected(let error): resolve.reject(error) case .fulfilled(let obj): resolve.fulfill(obj) } } }) } } #endif ================================================ FILE: Sources/Async.swift ================================================ #if swift(>=5.5) #if canImport(_Concurrency) @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *) public extension Guarantee { func async() async -> T { await withCheckedContinuation { continuation in done { value in continuation.resume(returning: value) } } } } @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *) public extension Promise { func async() async throws -> T { try await withCheckedThrowingContinuation { continuation in done { value in continuation.resume(returning: value) }.catch(policy: .allErrors) { error in continuation.resume(throwing: error) } } } } #endif #endif ================================================ FILE: Sources/Box.swift ================================================ import Dispatch enum Sealant { case pending(Handlers) case resolved(R) } final class Handlers { var bodies: [(R) -> Void] = [] func append(_ item: @escaping(R) -> Void) { bodies.append(item) } } /// - Remark: not protocol ∵ http://www.russbishop.net/swift-associated-types-cont class Box { func inspect() -> Sealant { fatalError() } func inspect(_: (Sealant) -> Void) { fatalError() } func seal(_: T) {} } final class SealedBox: Box { let value: T init(value: T) { self.value = value } override func inspect() -> Sealant { return .resolved(value) } } class EmptyBox: Box { private var sealant = Sealant.pending(.init()) private let barrier = DispatchQueue(label: "org.promisekit.barrier", attributes: .concurrent) override func seal(_ value: T) { var handlers: Handlers! barrier.sync(flags: .barrier) { guard case .pending(let _handlers) = self.sealant else { return // already fulfilled! } handlers = _handlers self.sealant = .resolved(value) } //FIXME we are resolved so should `pipe(to:)` be called at this instant, “thens are called in order” would be invalid //NOTE we don’t do this in the above `sync` because that could potentially deadlock //THOUGH since `then` etc. typically invoke after a run-loop cycle, this issue is somewhat less severe if let handlers = handlers { handlers.bodies.forEach{ $0(value) } } //TODO solution is an unfortunate third state “sealed” where then's get added // to a separate handler pool for that state // any other solution has potential races } override func inspect() -> Sealant { var rv: Sealant! barrier.sync { rv = self.sealant } return rv } override func inspect(_ body: (Sealant) -> Void) { var sealed = false barrier.sync(flags: .barrier) { switch sealant { case .pending: // body will append to handlers, so we must stay barrier’d body(sealant) case .resolved: sealed = true } } if sealed { // we do this outside the barrier to prevent potential deadlocks // it's safe because we never transition away from this state body(sealant) } } } extension Optional where Wrapped: DispatchQueue { @inline(__always) func async(flags: DispatchWorkItemFlags?, _ body: @escaping() -> Void) { switch self { case .none: body() case .some(let q): if let flags = flags { q.async(flags: flags, execute: body) } else { q.async(execute: body) } } } } ================================================ FILE: Sources/Catchable.swift ================================================ import Dispatch /// Provides `catch` and `recover` to your object that conforms to `Thenable` public protocol CatchMixin: Thenable {} public extension CatchMixin { /** The provided closure executes when this promise rejects. Rejecting a promise cascades: rejecting all subsequent promises (unless recover is invoked) thus you will typically place your catch at the end of a chain. Often utility promises will not have a catch, instead delegating the error handling to the caller. - Parameter on: The queue to which the provided closure dispatches. - Parameter policy: The default policy does not execute your handler for cancellation errors. - Parameter execute: The handler to execute if this promise is rejected. - Returns: A promise finalizer. - SeeAlso: [Cancellation](https://github.com/mxcl/PromiseKit/blob/master/Documentation/CommonPatterns.md#cancellation) */ @discardableResult func `catch`(on: DispatchQueue? = conf.Q.return, flags: DispatchWorkItemFlags? = nil, policy: CatchPolicy = conf.catchPolicy, _ body: @escaping(Error) -> Void) -> PMKFinalizer { let finalizer = PMKFinalizer() pipe { switch $0 { case .rejected(let error): guard policy == .allErrors || !error.isCancelled else { fallthrough } on.async(flags: flags) { body(error) finalizer.pending.resolve(()) } case .fulfilled: finalizer.pending.resolve(()) } } return finalizer } } public class PMKFinalizer { let pending = Guarantee.pending() /// `finally` is the same as `ensure`, but it is not chainable public func finally(on: DispatchQueue? = conf.Q.return, flags: DispatchWorkItemFlags? = nil, _ body: @escaping () -> Void) { pending.guarantee.done(on: on, flags: flags) { body() } } } public extension CatchMixin { /** The provided closure executes when this promise rejects. Unlike `catch`, `recover` continues the chain. Use `recover` in circumstances where recovering the chain from certain errors is a possibility. For example: firstly { CLLocationManager.requestLocation() }.recover { error in guard error == CLError.unknownLocation else { throw error } return .value(CLLocation.chicago) } - Parameter on: The queue to which the provided closure dispatches. - Parameter body: The handler to execute if this promise is rejected. - SeeAlso: [Cancellation](https://github.com/mxcl/PromiseKit/blob/master/Documentation/CommonPatterns.md#cancellation) */ func recover(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, policy: CatchPolicy = conf.catchPolicy, _ body: @escaping(Error) throws -> U) -> Promise where U.T == T { let rp = Promise(.pending) pipe { switch $0 { case .fulfilled(let value): rp.box.seal(.fulfilled(value)) case .rejected(let error): if policy == .allErrors || !error.isCancelled { on.async(flags: flags) { do { let rv = try body(error) guard rv !== rp else { throw PMKError.returnedSelf } rv.pipe(to: rp.box.seal) } catch { rp.box.seal(.rejected(error)) } } } else { rp.box.seal(.rejected(error)) } } } return rp } /** The provided closure executes when this promise rejects. This variant of `recover` requires the handler to return a Guarantee, thus it returns a Guarantee itself and your closure cannot `throw`. - Note it is logically impossible for this to take a `catchPolicy`, thus `allErrors` are handled. - Parameter on: The queue to which the provided closure dispatches. - Parameter body: The handler to execute if this promise is rejected. - SeeAlso: [Cancellation](https://github.com/mxcl/PromiseKit/blob/master/Documentation/CommonPatterns.md#cancellation) */ @discardableResult func recover(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, _ body: @escaping(Error) -> Guarantee) -> Guarantee { let rg = Guarantee(.pending) pipe { switch $0 { case .fulfilled(let value): rg.box.seal(value) case .rejected(let error): on.async(flags: flags) { body(error).pipe(to: rg.box.seal) } } } return rg } /** The provided closure executes when this promise resolves, whether it rejects or not. firstly { UIApplication.shared.networkActivityIndicatorVisible = true }.done { //… }.ensure { UIApplication.shared.networkActivityIndicatorVisible = false }.catch { //… } - Parameter on: The queue to which the provided closure dispatches. - Parameter body: The closure that executes when this promise resolves. - Returns: A new promise, resolved with this promise’s resolution. */ func ensure(on: DispatchQueue? = conf.Q.return, flags: DispatchWorkItemFlags? = nil, _ body: @escaping () -> Void) -> Promise { let rp = Promise(.pending) pipe { result in on.async(flags: flags) { body() rp.box.seal(result) } } return rp } /** The provided closure executes when this promise resolves, whether it rejects or not. The chain waits on the returned `Guarantee`. firstly { setup() }.done { //… }.ensureThen { teardown() // -> Guarante }.catch { //… } - Parameter on: The queue to which the provided closure dispatches. - Parameter body: The closure that executes when this promise resolves. - Returns: A new promise, resolved with this promise’s resolution. */ func ensureThen(on: DispatchQueue? = conf.Q.return, flags: DispatchWorkItemFlags? = nil, _ body: @escaping () -> Guarantee) -> Promise { let rp = Promise(.pending) pipe { result in on.async(flags: flags) { body().done { rp.box.seal(result) } } } return rp } /** Consumes the Swift unused-result warning. - Note: You should `catch`, but in situations where you know you don’t need a `catch`, `cauterize` makes your intentions clear. */ @discardableResult func cauterize() -> PMKFinalizer { return self.catch { conf.logHandler(.cauterized($0)) } } } public extension CatchMixin where T == Void { /** The provided closure executes when this promise rejects. This variant of `recover` is specialized for `Void` promises and de-errors your chain returning a `Guarantee`, thus you cannot `throw` and you must handle all errors including cancellation. - Parameter on: The queue to which the provided closure dispatches. - Parameter body: The handler to execute if this promise is rejected. - SeeAlso: [Cancellation](https://github.com/mxcl/PromiseKit/blob/master/Documentation/CommonPatterns.md#cancellation) */ @discardableResult func recover(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, _ body: @escaping(Error) -> Void) -> Guarantee { let rg = Guarantee(.pending) pipe { switch $0 { case .fulfilled: rg.box.seal(()) case .rejected(let error): on.async(flags: flags) { body(error) rg.box.seal(()) } } } return rg } /** The provided closure executes when this promise rejects. This variant of `recover` ensures that no error is thrown from the handler and allows specifying a catch policy. - Parameter on: The queue to which the provided closure dispatches. - Parameter body: The handler to execute if this promise is rejected. - SeeAlso: [Cancellation](https://github.com/mxcl/PromiseKit/blob/master/Documentation/CommonPatterns.md#cancellation) */ func recover(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, policy: CatchPolicy = conf.catchPolicy, _ body: @escaping(Error) throws -> Void) -> Promise { let rg = Promise(.pending) pipe { switch $0 { case .fulfilled: rg.box.seal(.fulfilled(())) case .rejected(let error): if policy == .allErrors || !error.isCancelled { on.async(flags: flags) { do { rg.box.seal(.fulfilled(try body(error))) } catch { rg.box.seal(.rejected(error)) } } } else { rg.box.seal(.rejected(error)) } } } return rg } } ================================================ FILE: Sources/Combine.swift ================================================ #if swift(>=4.1) #if canImport(Combine) import Combine @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *) public extension Guarantee { func future() -> Future { .init { [weak self] promise in self?.done { value in promise(.success(value)) } } } } @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *) public extension Promise { func future() -> Future { .init { [weak self] promise in self?.done { value in promise(.success(value)) }.catch { error in promise(.failure(error)) } } } } @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *) public extension Future { func promise() -> PromiseKit.Promise { return .init { [weak self] resolver in var cancellable: AnyCancellable? cancellable = self?.sink(receiveCompletion: { completion in cancellable?.cancel() cancellable = nil switch completion { case .failure(let error): resolver.reject(error) case .finished: break } }, receiveValue: { value in cancellable?.cancel() cancellable = nil resolver.fulfill(value) }) } } } @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *) public extension Future where Failure == Never { func guarantee() -> Guarantee { return .init { [weak self] resolver in var cancellable: AnyCancellable? cancellable = self?.sink(receiveValue: { value in cancellable?.cancel() cancellable = nil resolver(value) }) } } } #endif #endif ================================================ FILE: Sources/Configuration.swift ================================================ import Dispatch /** PromiseKit’s configurable parameters. Do not change these after any Promise machinery executes as the configuration object is not thread-safe. We would like it to be, but sadly `Swift` does not expose `dispatch_once` et al. which is what we used to use in order to make the configuration immutable once first used. */ public struct PMKConfiguration { /// The default queues that promises handlers dispatch to public var Q: (map: DispatchQueue?, return: DispatchQueue?) = (map: DispatchQueue.main, return: DispatchQueue.main) /// The default catch-policy for all `catch` and `resolve` public var catchPolicy = CatchPolicy.allErrorsExceptCancellation /// The closure used to log PromiseKit events. /// Not thread safe; change before processing any promises. /// - Note: The default handler calls `print()` public var logHandler: (LogEvent) -> Void = { event in switch event { case .waitOnMainThread: print("PromiseKit: warning: `wait()` called on main thread!") case .pendingPromiseDeallocated: print("PromiseKit: warning: pending promise deallocated") case .pendingGuaranteeDeallocated: print("PromiseKit: warning: pending guarantee deallocated") case .cauterized (let error): print("PromiseKit:cauterized-error: \(error)") } } } /// Modify this as soon as possible in your application’s lifetime public var conf = PMKConfiguration() ================================================ FILE: Sources/CustomStringConvertible.swift ================================================ extension Promise: CustomStringConvertible { /// - Returns: A description of the state of this promise. public var description: String { switch result { case nil: return "Promise(…\(T.self))" case .rejected(let error)?: return "Promise(\(error))" case .fulfilled(let value)?: return "Promise(\(value))" } } } extension Promise: CustomDebugStringConvertible { /// - Returns: A debug-friendly description of the state of this promise. public var debugDescription: String { switch box.inspect() { case .pending(let handlers): return "Promise<\(T.self)>.pending(handlers: \(handlers.bodies.count))" case .resolved(.rejected(let error)): return "Promise<\(T.self)>.rejected(\(type(of: error)).\(error))" case .resolved(.fulfilled(let value)): return "Promise<\(T.self)>.fulfilled(\(value))" } } } #if !SWIFT_PACKAGE extension AnyPromise { /// - Returns: A description of the state of this promise. override open var description: String { switch box.inspect() { case .pending: return "AnyPromise(…)" case .resolved(let obj?): return "AnyPromise(\(obj))" case .resolved(nil): return "AnyPromise(nil)" } } } #endif ================================================ FILE: Sources/Deprecations.swift ================================================ import Dispatch @available(*, deprecated, message: "See `init(resolver:)`") public func wrap(_ body: (@escaping (T?, Error?) -> Void) throws -> Void) -> Promise { return Promise { seal in try body(seal.resolve) } } @available(*, deprecated, message: "See `init(resolver:)`") public func wrap(_ body: (@escaping (T, Error?) -> Void) throws -> Void) -> Promise { return Promise { seal in try body(seal.resolve) } } @available(*, deprecated, message: "See `init(resolver:)`") public func wrap(_ body: (@escaping (Error?, T?) -> Void) throws -> Void) -> Promise { return Promise { seal in try body(seal.resolve) } } @available(*, deprecated, message: "See `init(resolver:)`") public func wrap(_ body: (@escaping (Error?) -> Void) throws -> Void) -> Promise { return Promise { seal in try body(seal.resolve) } } @available(*, deprecated, message: "See `init(resolver:)`") public func wrap(_ body: (@escaping (T) -> Void) throws -> Void) -> Promise { return Promise { seal in try body(seal.fulfill) } } public extension Promise { @available(*, deprecated, message: "See `ensure`") func always(on q: DispatchQueue = .main, execute body: @escaping () -> Void) -> Promise { return ensure(on: q, body) } } public extension Thenable { #if PMKFullDeprecations /// disabled due to ambiguity with the other `.flatMap` @available(*, deprecated, message: "See: `compactMap`") func flatMap(on: DispatchQueue? = conf.Q.map, _ transform: @escaping(T) throws -> U?) -> Promise { return compactMap(on: on, transform) } #endif } public extension Thenable where T: Sequence { #if PMKFullDeprecations /// disabled due to ambiguity with the other `.map` @available(*, deprecated, message: "See: `mapValues`") func map(on: DispatchQueue? = conf.Q.map, _ transform: @escaping(T.Iterator.Element) throws -> U) -> Promise<[U]> { return mapValues(on: on, transform) } /// disabled due to ambiguity with the other `.flatMap` @available(*, deprecated, message: "See: `flatMapValues`") func flatMap(on: DispatchQueue? = conf.Q.map, _ transform: @escaping(T.Iterator.Element) throws -> U) -> Promise<[U.Iterator.Element]> { return flatMapValues(on: on, transform) } #endif @available(*, deprecated, message: "See: `filterValues`") func filter(on: DispatchQueue? = conf.Q.map, test: @escaping (T.Iterator.Element) -> Bool) -> Promise<[T.Iterator.Element]> { return filterValues(on: on, test) } } public extension Thenable where T: Collection { @available(*, deprecated, message: "See: `firstValue`") var first: Promise { return firstValue } @available(*, deprecated, message: "See: `lastValue`") var last: Promise { return lastValue } } public extension Thenable where T: Sequence, T.Iterator.Element: Comparable { @available(*, deprecated, message: "See: `sortedValues`") func sorted(on: DispatchQueue? = conf.Q.map) -> Promise<[T.Iterator.Element]> { return sortedValues(on: on) } } ================================================ FILE: Sources/Error.swift ================================================ import Foundation public enum PMKError: Error { /** The completionHandler with form `(T?, Error?)` was called with `(nil, nil)`. This is invalid as per Cocoa/Apple calling conventions. */ case invalidCallingConvention /** A handler returned its own promise. 99% of the time, this is likely a programming error. It is also invalid per Promises/A+. */ case returnedSelf /** `when()`, `race()` etc. were called with invalid parameters, eg. an empty array. */ case badInput /// The operation was cancelled case cancelled /// `nil` was returned from `flatMap` @available(*, deprecated, message: "See: `compactMap`") case flatMap(Any, Any.Type) /// `nil` was returned from `compactMap` case compactMap(Any, Any.Type) /** The lastValue or firstValue of a sequence was requested but the sequence was empty. Also used if all values of this collection failed the test passed to `firstValue(where:)`. */ case emptySequence /// no winner in `race(fulfilled:)` case noWinner } extension PMKError: CustomDebugStringConvertible { public var debugDescription: String { switch self { case .flatMap(let obj, let type): return "Could not `flatMap<\(type)>`: \(obj)" case .compactMap(let obj, let type): return "Could not `compactMap<\(type)>`: \(obj)" case .invalidCallingConvention: return "A closure was called with an invalid calling convention, probably (nil, nil)" case .returnedSelf: return "A promise handler returned itself" case .badInput: return "Bad input was provided to a PromiseKit function" case .cancelled: return "The asynchronous sequence was cancelled" case .emptySequence: return "The first or last element was requested for an empty sequence" case .noWinner: return "All thenables passed to race(fulfilled:) were rejected" } } } extension PMKError: LocalizedError { public var errorDescription: String? { return debugDescription } } //////////////////////////////////////////////////////////// Cancellation /// An error that may represent the cancelled condition public protocol CancellableError: Error { /// returns true if this Error represents a cancelled condition var isCancelled: Bool { get } } extension Error { public var isCancelled: Bool { do { throw self } catch PMKError.cancelled { return true } catch let error as CancellableError { return error.isCancelled } catch URLError.cancelled { return true } catch CocoaError.userCancelled { return true } catch let error as NSError { #if os(macOS) || os(iOS) || os(tvOS) || os(watchOS) let domain = error.domain let code = error.code return ("SKErrorDomain", 2) == (domain, code) #else return false #endif } catch { return false } } } /// Used by `catch` and `recover` public enum CatchPolicy { /// Indicates that `catch` or `recover` handle all error types including cancellable-errors. case allErrors /// Indicates that `catch` or `recover` handle all error except cancellable-errors. case allErrorsExceptCancellation } ================================================ FILE: Sources/Guarantee.swift ================================================ import class Foundation.Thread import Dispatch /** A `Guarantee` is a functional abstraction around an asynchronous operation that cannot error. - See: `Thenable` */ public final class Guarantee: Thenable { let box: PromiseKit.Box fileprivate init(box: SealedBox) { self.box = box } /// Returns a `Guarantee` sealed with the provided value. public static func value(_ value: T) -> Guarantee { return .init(box: SealedBox(value: value)) } /// Returns a pending `Guarantee` that can be resolved with the provided closure’s parameter. public init(resolver body: (@escaping(T) -> Void) -> Void) { box = Box() body(box.seal) } /// - See: `Thenable.pipe` public func pipe(to: @escaping(Result) -> Void) { pipe{ to(.fulfilled($0)) } } func pipe(to: @escaping(T) -> Void) { switch box.inspect() { case .pending: box.inspect { switch $0 { case .pending(let handlers): handlers.append(to) case .resolved(let value): to(value) } } case .resolved(let value): to(value) } } /// - See: `Thenable.result` public var result: Result? { switch box.inspect() { case .pending: return nil case .resolved(let value): return .fulfilled(value) } } final private class Box: EmptyBox { deinit { switch inspect() { case .pending: PromiseKit.conf.logHandler(.pendingGuaranteeDeallocated) case .resolved: break } } } init(_: PMKUnambiguousInitializer) { box = Box() } /// Returns a tuple of a pending `Guarantee` and a function that resolves it. public class func pending() -> (guarantee: Guarantee, resolve: (T) -> Void) { return { ($0, $0.box.seal) }(Guarantee(.pending)) } } public extension Guarantee { @discardableResult func done(on: DispatchQueue? = conf.Q.return, flags: DispatchWorkItemFlags? = nil, _ body: @escaping(T) -> Void) -> Guarantee { let rg = Guarantee(.pending) pipe { (value: T) in on.async(flags: flags) { body(value) rg.box.seal(()) } } return rg } func get(on: DispatchQueue? = conf.Q.return, flags: DispatchWorkItemFlags? = nil, _ body: @escaping (T) -> Void) -> Guarantee { return map(on: on, flags: flags) { body($0) return $0 } } func map(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, _ body: @escaping(T) -> U) -> Guarantee { let rg = Guarantee(.pending) pipe { value in on.async(flags: flags) { rg.box.seal(body(value)) } } return rg } #if swift(>=4) && !swift(>=5.2) func map(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, _ keyPath: KeyPath) -> Guarantee { let rg = Guarantee(.pending) pipe { value in on.async(flags: flags) { rg.box.seal(value[keyPath: keyPath]) } } return rg } #endif @discardableResult func then(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, _ body: @escaping(T) -> Guarantee) -> Guarantee { let rg = Guarantee(.pending) pipe { value in on.async(flags: flags) { body(value).pipe(to: rg.box.seal) } } return rg } func asVoid() -> Guarantee { return map(on: nil) { _ in } } /** Blocks this thread, so you know, don’t call this on a serial thread that any part of your chain may use. Like the main thread for example. */ func wait() -> T { if Thread.isMainThread { conf.logHandler(.waitOnMainThread) } var result = value if result == nil { let group = DispatchGroup() group.enter() pipe { (foo: T) in result = foo; group.leave() } group.wait() } return result! } } public extension Guarantee where T: Sequence { /** `Guarantee<[T]>` => `T` -> `U` => `Guarantee<[U]>` Guarantee.value([1,2,3]) .mapValues { integer in integer * 2 } .done { // $0 => [2,4,6] } */ func mapValues(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, _ transform: @escaping(T.Iterator.Element) -> U) -> Guarantee<[U]> { return map(on: on, flags: flags) { $0.map(transform) } } #if swift(>=4) && !swift(>=5.2) /** `Guarantee<[T]>` => `KeyPath` => `Guarantee<[U]>` Guarantee.value([Person(name: "Max"), Person(name: "Roman"), Person(name: "John")]) .mapValues(\.name) .done { // $0 => ["Max", "Roman", "John"] } */ func mapValues(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, _ keyPath: KeyPath) -> Guarantee<[U]> { return map(on: on, flags: flags) { $0.map { $0[keyPath: keyPath] } } } #endif /** `Guarantee<[T]>` => `T` -> `[U]` => `Guarantee<[U]>` Guarantee.value([1,2,3]) .flatMapValues { integer in [integer, integer] } .done { // $0 => [1,1,2,2,3,3] } */ func flatMapValues(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, _ transform: @escaping(T.Iterator.Element) -> U) -> Guarantee<[U.Iterator.Element]> { return map(on: on, flags: flags) { (foo: T) in foo.flatMap { transform($0) } } } /** `Guarantee<[T]>` => `T` -> `U?` => `Guarantee<[U]>` Guarantee.value(["1","2","a","3"]) .compactMapValues { Int($0) } .done { // $0 => [1,2,3] } */ func compactMapValues(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, _ transform: @escaping(T.Iterator.Element) -> U?) -> Guarantee<[U]> { return map(on: on, flags: flags) { foo -> [U] in #if !swift(>=3.3) || (swift(>=4) && !swift(>=4.1)) return foo.flatMap(transform) #else return foo.compactMap(transform) #endif } } #if swift(>=4) && !swift(>=5.2) /** `Guarantee<[T]>` => `KeyPath` => `Guarantee<[U]>` Guarantee.value([Person(name: "Max"), Person(name: "Roman", age: 26), Person(name: "John", age: 23)]) .compactMapValues(\.age) .done { // $0 => [26, 23] } */ func compactMapValues(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, _ keyPath: KeyPath) -> Guarantee<[U]> { return map(on: on, flags: flags) { foo -> [U] in #if !swift(>=4.1) return foo.flatMap { $0[keyPath: keyPath] } #else return foo.compactMap { $0[keyPath: keyPath] } #endif } } #endif /** `Guarantee<[T]>` => `T` -> `Guarantee` => `Guaranetee<[U]>` Guarantee.value([1,2,3]) .thenMap { .value($0 * 2) } .done { // $0 => [2,4,6] } */ func thenMap(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, _ transform: @escaping(T.Iterator.Element) -> Guarantee) -> Guarantee<[U]> { return then(on: on, flags: flags) { when(fulfilled: $0.map(transform)) }.recover { // if happens then is bug inside PromiseKit fatalError(String(describing: $0)) } } /** `Guarantee<[T]>` => `T` -> `Guarantee<[U]>` => `Guarantee<[U]>` Guarantee.value([1,2,3]) .thenFlatMap { integer in .value([integer, integer]) } .done { // $0 => [1,1,2,2,3,3] } */ func thenFlatMap(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, _ transform: @escaping(T.Iterator.Element) -> U) -> Guarantee<[U.T.Iterator.Element]> where U.T: Sequence { return then(on: on, flags: flags) { when(fulfilled: $0.map(transform)) }.map(on: nil) { $0.flatMap { $0 } }.recover { // if happens then is bug inside PromiseKit fatalError(String(describing: $0)) } } /** `Guarantee<[T]>` => `T` -> Bool => `Guarantee<[T]>` Guarantee.value([1,2,3]) .filterValues { $0 > 1 } .done { // $0 => [2,3] } */ func filterValues(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, _ isIncluded: @escaping(T.Iterator.Element) -> Bool) -> Guarantee<[T.Iterator.Element]> { return map(on: on, flags: flags) { $0.filter(isIncluded) } } #if swift(>=4) && !swift(>=5.2) /** `Guarantee<[T]>` => `KeyPath` => `Guarantee<[T]>` Guarantee.value([Person(name: "Max"), Person(name: "Roman", age: 26, isStudent: false), Person(name: "John", age: 23, isStudent: true)]) .filterValues(\.isStudent) .done { // $0 => [Person(name: "John", age: 23, isStudent: true)] } */ func filterValues(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, _ keyPath: KeyPath) -> Guarantee<[T.Iterator.Element]> { return map(on: on, flags: flags) { $0.filter { $0[keyPath: keyPath] } } } #endif /** `Guarantee<[T]>` => (`T`, `T`) -> Bool => `Guarantee<[T]>` Guarantee.value([5,2,3,4,1]) .sortedValues { $0 > $1 } .done { // $0 => [5,4,3,2,1] } */ func sortedValues(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, _ areInIncreasingOrder: @escaping(T.Iterator.Element, T.Iterator.Element) -> Bool) -> Guarantee<[T.Iterator.Element]> { return map(on: on, flags: flags) { $0.sorted(by: areInIncreasingOrder) } } } public extension Guarantee where T: Sequence, T.Iterator.Element: Comparable { /** `Guarantee<[T]>` => `Guarantee<[T]>` Guarantee.value([5,2,3,4,1]) .sortedValues() .done { // $0 => [1,2,3,4,5] } */ func sortedValues(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil) -> Guarantee<[T.Iterator.Element]> { return map(on: on, flags: flags) { $0.sorted() } } } #if swift(>=3.1) public extension Guarantee where T == Void { convenience init() { self.init(box: SealedBox(value: Void())) } static var value: Guarantee { return .value(Void()) } } #endif public extension DispatchQueue { /** Asynchronously executes the provided closure on a dispatch queue. DispatchQueue.global().async(.promise) { md5(input) }.done { md5 in //… } - Parameter body: The closure that resolves this promise. - Returns: A new `Guarantee` resolved by the result of the provided closure. - Note: There is no Promise/Thenable version of this due to Swift compiler ambiguity issues. */ @available(macOS 10.10, iOS 2.0, tvOS 10.0, watchOS 2.0, *) final func async(_: PMKNamespacer, group: DispatchGroup? = nil, qos: DispatchQoS = .default, flags: DispatchWorkItemFlags = [], execute body: @escaping () -> T) -> Guarantee { let rg = Guarantee(.pending) async(group: group, qos: qos, flags: flags) { rg.box.seal(body()) } return rg } } #if os(Linux) import func CoreFoundation._CFIsMainThread extension Thread { // `isMainThread` is not implemented yet in swift-corelibs-foundation. static var isMainThread: Bool { return _CFIsMainThread() } } #endif ================================================ FILE: Sources/Info.plist ================================================ CFBundleDevelopmentRegion en CFBundleExecutable $(EXECUTABLE_NAME) CFBundleIdentifier $(PRODUCT_BUNDLE_IDENTIFIER) CFBundleInfoDictionaryVersion 6.0 CFBundleName $(PRODUCT_NAME) CFBundlePackageType $(PRODUCT_BUNDLE_PACKAGE_TYPE) CFBundleShortVersionString $(CURRENT_PROJECT_VERSION) CFBundleSignature ???? CFBundleVersion 1 UISupportedInterfaceOrientations UIInterfaceOrientationPortrait ================================================ FILE: Sources/LogEvent.swift ================================================ /** The PromiseKit events which may be logged. ```` /// A promise or guarantee has blocked the main thread case waitOnMainThread /// A promise has been deallocated without being resolved case pendingPromiseDeallocated /// An error which occurred while fulfilling a promise was swallowed case cauterized(Error) /// Errors which give a string error message case misc (String) ```` */ public enum LogEvent { /// A promise or guarantee has blocked the main thread case waitOnMainThread /// A promise has been deallocated without being resolved case pendingPromiseDeallocated /// A guarantee has been deallocated without being resolved case pendingGuaranteeDeallocated /// An error which occurred while resolving a promise was swallowed case cauterized(Error) } ================================================ FILE: Sources/NSMethodSignatureForBlock.m ================================================ #import struct PMKBlockLiteral { void *isa; // initialized to &_NSConcreteStackBlock or &_NSConcreteGlobalBlock int flags; int reserved; void (*invoke)(void *, ...); struct block_descriptor { unsigned long int reserved; // NULL unsigned long int size; // sizeof(struct Block_literal_1) // optional helper functions void (*copy_helper)(void *dst, void *src); // IFF (1<<25) void (*dispose_helper)(void *src); // IFF (1<<25) // required ABI.2010.3.16 const char *signature; // IFF (1<<30) } *descriptor; // imported variables }; typedef NS_OPTIONS(NSUInteger, PMKBlockDescriptionFlags) { PMKBlockDescriptionFlagsHasCopyDispose = (1 << 25), PMKBlockDescriptionFlagsHasCtor = (1 << 26), // helpers have C++ code PMKBlockDescriptionFlagsIsGlobal = (1 << 28), PMKBlockDescriptionFlagsHasStret = (1 << 29), // IFF BLOCK_HAS_SIGNATURE PMKBlockDescriptionFlagsHasSignature = (1 << 30) }; // It appears 10.7 doesn't support quotes in method signatures. Remove them // via @rabovik's method. See https://github.com/OliverLetterer/SLObjectiveCRuntimeAdditions/pull/2 #if defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && __MAC_OS_X_VERSION_MIN_REQUIRED < __MAC_10_8 NS_INLINE static const char * pmk_removeQuotesFromMethodSignature(const char *str){ char *result = malloc(strlen(str) + 1); BOOL skip = NO; char *to = result; char c; while ((c = *str++)) { if ('"' == c) { skip = !skip; continue; } if (skip) continue; *to++ = c; } *to = '\0'; return result; } #endif static NSMethodSignature *NSMethodSignatureForBlock(id block) { if (!block) return nil; struct PMKBlockLiteral *blockRef = (__bridge struct PMKBlockLiteral *)block; PMKBlockDescriptionFlags flags = (PMKBlockDescriptionFlags)blockRef->flags; if (flags & PMKBlockDescriptionFlagsHasSignature) { void *signatureLocation = blockRef->descriptor; signatureLocation += sizeof(unsigned long int); signatureLocation += sizeof(unsigned long int); if (flags & PMKBlockDescriptionFlagsHasCopyDispose) { signatureLocation += sizeof(void(*)(void *dst, void *src)); signatureLocation += sizeof(void (*)(void *src)); } const char *signature = (*(const char **)signatureLocation); #if defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && __MAC_OS_X_VERSION_MIN_REQUIRED < __MAC_10_8 signature = pmk_removeQuotesFromMethodSignature(signature); NSMethodSignature *nsSignature = [NSMethodSignature signatureWithObjCTypes:signature]; free((void *)signature); return nsSignature; #endif return [NSMethodSignature signatureWithObjCTypes:signature]; } return 0; } ================================================ FILE: Sources/PMKCallVariadicBlock.m ================================================ #import "NSMethodSignatureForBlock.m" #import #import #import "AnyPromise+Private.h" #import #import #import #ifndef PMKLog #define PMKLog NSLog #endif @interface PMKArray : NSObject { @public id objs[3]; NSUInteger count; } @end @implementation PMKArray - (id)objectAtIndexedSubscript:(NSUInteger)idx { if (count <= idx) { // this check is necessary due to lack of checks in `pmk_safely_call_block` return nil; } return objs[idx]; } @end id __PMKArrayWithCount(NSUInteger count, ...) { PMKArray *this = [PMKArray new]; this->count = count; va_list args; va_start(args, count); for (NSUInteger x = 0; x < count; ++x) this->objs[x] = va_arg(args, id); va_end(args); return this; } static inline id _PMKCallVariadicBlock(id frock, id result) { NSCAssert(frock, @""); NSMethodSignature *sig = NSMethodSignatureForBlock(frock); const NSUInteger nargs = sig.numberOfArguments; const char rtype = sig.methodReturnType[0]; #define call_block_with_rtype(type) ({^type{ \ switch (nargs) { \ case 1: \ return ((type(^)(void))frock)(); \ case 2: { \ const id arg = [result class] == [PMKArray class] ? result[0] : result; \ return ((type(^)(id))frock)(arg); \ } \ case 3: { \ type (^block)(id, id) = frock; \ return [result class] == [PMKArray class] \ ? block(result[0], result[1]) \ : block(result, nil); \ } \ case 4: { \ type (^block)(id, id, id) = frock; \ return [result class] == [PMKArray class] \ ? block(result[0], result[1], result[2]) \ : block(result, nil, nil); \ } \ default: \ @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"PromiseKit: The provided block’s argument count is unsupported." userInfo:nil]; \ }}();}) switch (rtype) { case 'v': call_block_with_rtype(void); return nil; case '@': return call_block_with_rtype(id) ?: nil; case '*': { char *str = call_block_with_rtype(char *); return str ? @(str) : nil; } case 'c': return @(call_block_with_rtype(char)); case 'i': return @(call_block_with_rtype(int)); case 's': return @(call_block_with_rtype(short)); case 'l': return @(call_block_with_rtype(long)); case 'q': return @(call_block_with_rtype(long long)); case 'C': return @(call_block_with_rtype(unsigned char)); case 'I': return @(call_block_with_rtype(unsigned int)); case 'S': return @(call_block_with_rtype(unsigned short)); case 'L': return @(call_block_with_rtype(unsigned long)); case 'Q': return @(call_block_with_rtype(unsigned long long)); case 'f': return @(call_block_with_rtype(float)); case 'd': return @(call_block_with_rtype(double)); case 'B': return @(call_block_with_rtype(_Bool)); case '^': if (strcmp(sig.methodReturnType, "^v") == 0) { call_block_with_rtype(void); return nil; } // else fall through! default: @throw [NSException exceptionWithName:@"PromiseKit" reason:@"PromiseKit: Unsupported method signature." userInfo:nil]; } } static id PMKCallVariadicBlock(id frock, id result) { @try { return _PMKCallVariadicBlock(frock, result); } @catch (id thrown) { if ([thrown isKindOfClass:[NSString class]]) return thrown; if ([thrown isKindOfClass:[NSError class]]) return thrown; // we don’t catch objc exceptions: they are meant to crash your app @throw thrown; } } ================================================ FILE: Sources/Promise.swift ================================================ import class Foundation.Thread import Dispatch /** A `Promise` is a functional abstraction around a failable asynchronous operation. - See: `Thenable` */ public final class Promise: Thenable, CatchMixin { let box: Box> fileprivate init(box: SealedBox>) { self.box = box } /** Initialize a new fulfilled promise. We do not provide `init(value:)` because Swift is “greedy” and would pick that initializer in cases where it should pick one of the other more specific options leading to Promises with `T` that is eg: `Error` or worse `(T->Void,Error->Void)` for uses of our PMK < 4 pending initializer due to Swift trailing closure syntax (nothing good comes without pain!). Though often easy to detect, sometimes these issues would be hidden by other type inference leading to some nasty bugs in production. In PMK5 we tried to work around this by making the pending initializer take the form `Promise(.pending)` but this led to bad migration errors for PMK4 users. Hence instead we quickly released PMK6 and now only provide this initializer for making sealed & fulfilled promises. Usage is still (usually) good: guard foo else { return .value(bar) } */ public static func value(_ value: T) -> Promise { return Promise(box: SealedBox(value: .fulfilled(value))) } /// Initialize a new rejected promise. public init(error: Error) { box = SealedBox(value: .rejected(error)) } /// Initialize a new promise bound to the provided `Thenable`. public init(_ bridge: U) where U.T == T { box = EmptyBox() bridge.pipe(to: box.seal) } /// Initialize a new promise that can be resolved with the provided `Resolver`. public init(resolver body: (Resolver) throws -> Void) { box = EmptyBox() let resolver = Resolver(box) do { try body(resolver) } catch { resolver.reject(error) } } /// - Returns: a tuple of a new pending promise and its `Resolver`. public class func pending() -> (promise: Promise, resolver: Resolver) { return { ($0, Resolver($0.box)) }(Promise(.pending)) } /// - See: `Thenable.pipe` public func pipe(to: @escaping(Result) -> Void) { switch box.inspect() { case .pending: box.inspect { switch $0 { case .pending(let handlers): handlers.append(to) case .resolved(let value): to(value) } } case .resolved(let value): to(value) } } /// - See: `Thenable.result` public var result: Result? { switch box.inspect() { case .pending: return nil case .resolved(let result): return result } } init(_: PMKUnambiguousInitializer) { box = EmptyBox() } } public extension Promise { /** Blocks this thread, so—you know—don’t call this on a serial thread that any part of your chain may use. Like the main thread for example. */ func wait() throws -> T { if Thread.isMainThread { conf.logHandler(LogEvent.waitOnMainThread) } var result = self.result if result == nil { let group = DispatchGroup() group.enter() pipe { result = $0; group.leave() } group.wait() } switch result! { case .rejected(let error): throw error case .fulfilled(let value): return value } } } #if swift(>=3.1) extension Promise where T == Void { /// Initializes a new promise fulfilled with `Void` public convenience init() { self.init(box: SealedBox(value: .fulfilled(Void()))) } /// Returns a new promise fulfilled with `Void` public static var value: Promise { return .value(Void()) } } #endif public extension DispatchQueue { /** Asynchronously executes the provided closure on a dispatch queue. DispatchQueue.global().async(.promise) { try md5(input) }.done { md5 in //… } - Parameter body: The closure that resolves this promise. - Returns: A new `Promise` resolved by the result of the provided closure. - Note: There is no Promise/Thenable version of this due to Swift compiler ambiguity issues. */ @available(macOS 10.10, iOS 8.0, tvOS 9.0, watchOS 2.0, *) final func async(_: PMKNamespacer, group: DispatchGroup? = nil, qos: DispatchQoS = .default, flags: DispatchWorkItemFlags = [], execute body: @escaping () throws -> T) -> Promise { let promise = Promise(.pending) async(group: group, qos: qos, flags: flags) { do { promise.box.seal(.fulfilled(try body())) } catch { promise.box.seal(.rejected(error)) } } return promise } } /// used by our extensions to provide unambiguous functions with the same name as the original function public enum PMKNamespacer { case promise } enum PMKUnambiguousInitializer { case pending } ================================================ FILE: Sources/PromiseKit.h ================================================ #import #import #import // `FOUNDATION_EXPORT` FOUNDATION_EXPORT double PromiseKitVersionNumber; FOUNDATION_EXPORT const unsigned char PromiseKitVersionString[]; ================================================ FILE: Sources/Resolver.swift ================================================ /// An object for resolving promises public final class Resolver { let box: Box> init(_ box: Box>) { self.box = box } deinit { if case .pending = box.inspect() { conf.logHandler(.pendingPromiseDeallocated) } } } public extension Resolver { /// Fulfills the promise with the provided value func fulfill(_ value: T) { box.seal(.fulfilled(value)) } /// Rejects the promise with the provided error func reject(_ error: Error) { box.seal(.rejected(error)) } /// Resolves the promise with the provided result func resolve(_ result: Result) { box.seal(result) } /// Resolves the promise with the provided value or error func resolve(_ obj: T?, _ error: Error?) { if let error = error { reject(error) } else if let obj = obj { fulfill(obj) } else { reject(PMKError.invalidCallingConvention) } } /// Fulfills the promise with the provided value unless the provided error is non-nil func resolve(_ obj: T, _ error: Error?) { if let error = error { reject(error) } else { fulfill(obj) } } /// Resolves the promise, provided for non-conventional value-error ordered completion handlers. func resolve(_ error: Error?, _ obj: T?) { resolve(obj, error) } } #if swift(>=3.1) extension Resolver where T == Void { /// Fulfills the promise unless error is non-nil public func resolve(_ error: Error?) { if let error = error { reject(error) } else { fulfill(()) } } #if false // disabled ∵ https://github.com/mxcl/PromiseKit/issues/990 /// Fulfills the promise public func fulfill() { self.fulfill(()) } #else /// Fulfills the promise /// - Note: underscore is present due to: https://github.com/mxcl/PromiseKit/issues/990 public func fulfill_() { self.fulfill(()) } #endif } #endif #if swift(>=5.0) extension Resolver { /// Resolves the promise with the provided result public func resolve(_ result: Swift.Result) { switch result { case .failure(let error): self.reject(error) case .success(let value): self.fulfill(value) } } } #endif public enum Result { case fulfilled(T) case rejected(Error) } public extension PromiseKit.Result { var isFulfilled: Bool { switch self { case .fulfilled: return true case .rejected: return false } } } ================================================ FILE: Sources/Resources/PrivacyInfo.xcprivacy ================================================ NSPrivacyTracking NSPrivacyCollectedDataTypes ================================================ FILE: Sources/Thenable.swift ================================================ import Dispatch /// Thenable represents an asynchronous operation that can be chained. public protocol Thenable: AnyObject { /// The type of the wrapped value associatedtype T /// `pipe` is immediately executed when this `Thenable` is resolved func pipe(to: @escaping(Result) -> Void) /// The resolved result or nil if pending. var result: Result? { get } } public extension Thenable { /** The provided closure executes when this promise is fulfilled. This allows chaining promises. The promise returned by the provided closure is resolved before the promise returned by this closure resolves. - Parameter on: The queue to which the provided closure dispatches. - Parameter body: The closure that executes when this promise is fulfilled. It must return a promise. - Returns: A new promise that resolves when the promise returned from the provided closure resolves. For example: firstly { URLSession.shared.dataTask(.promise, with: url1) }.then { response in transform(data: response.data) }.done { transformation in //… } */ func then(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, _ body: @escaping(T) throws -> U) -> Promise { let rp = Promise(.pending) pipe { switch $0 { case .fulfilled(let value): on.async(flags: flags) { do { let rv = try body(value) guard rv !== rp else { throw PMKError.returnedSelf } rv.pipe(to: rp.box.seal) } catch { rp.box.seal(.rejected(error)) } } case .rejected(let error): rp.box.seal(.rejected(error)) } } return rp } /** The provided closure is executed when this promise is fulfilled. This is like `then` but it requires the closure to return a non-promise. - Parameter on: The queue to which the provided closure dispatches. - Parameter transform: The closure that is executed when this Promise is fulfilled. It must return a non-promise. - Returns: A new promise that is fulfilled with the value returned from the provided closure or rejected if the provided closure throws. For example: firstly { URLSession.shared.dataTask(.promise, with: url1) }.map { response in response.data.length }.done { length in //… } */ func map(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, _ transform: @escaping(T) throws -> U) -> Promise { let rp = Promise(.pending) pipe { switch $0 { case .fulfilled(let value): on.async(flags: flags) { do { rp.box.seal(.fulfilled(try transform(value))) } catch { rp.box.seal(.rejected(error)) } } case .rejected(let error): rp.box.seal(.rejected(error)) } } return rp } #if swift(>=4) && !swift(>=5.2) /** Similar to func `map(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, _ transform: @escaping(T) throws -> U) -> Promise`, but accepts a key path instead of a closure. - Parameter on: The queue to which the provided key path for value dispatches. - Parameter keyPath: The key path to the value that is using when this Promise is fulfilled. - Returns: A new promise that is fulfilled with the value for the provided key path. */ func map(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, _ keyPath: KeyPath) -> Promise { let rp = Promise(.pending) pipe { switch $0 { case .fulfilled(let value): on.async(flags: flags) { rp.box.seal(.fulfilled(value[keyPath: keyPath])) } case .rejected(let error): rp.box.seal(.rejected(error)) } } return rp } #endif /** The provided closure is executed when this promise is fulfilled. In your closure return an `Optional`, if you return `nil` the resulting promise is rejected with `PMKError.compactMap`, otherwise the promise is fulfilled with the unwrapped value. firstly { URLSession.shared.dataTask(.promise, with: url) }.compactMap { try JSONSerialization.jsonObject(with: $0.data) as? [String: String] }.done { dictionary in //… }.catch { // either `PMKError.compactMap` or a `JSONError` } */ func compactMap(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, _ transform: @escaping(T) throws -> U?) -> Promise { let rp = Promise(.pending) pipe { switch $0 { case .fulfilled(let value): on.async(flags: flags) { do { if let rv = try transform(value) { rp.box.seal(.fulfilled(rv)) } else { throw PMKError.compactMap(value, U.self) } } catch { rp.box.seal(.rejected(error)) } } case .rejected(let error): rp.box.seal(.rejected(error)) } } return rp } #if swift(>=4) && !swift(>=5.2) /** Similar to func `compactMap(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, _ transform: @escaping(T) throws -> U?) -> Promise`, but accepts a key path instead of a closure. - Parameter on: The queue to which the provided key path for value dispatches. - Parameter keyPath: The key path to the value that is using when this Promise is fulfilled. If the value for `keyPath` is `nil` the resulting promise is rejected with `PMKError.compactMap`. - Returns: A new promise that is fulfilled with the value for the provided key path. */ func compactMap(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, _ keyPath: KeyPath) -> Promise { let rp = Promise(.pending) pipe { switch $0 { case .fulfilled(let value): on.async(flags: flags) { do { if let rv = value[keyPath: keyPath] { rp.box.seal(.fulfilled(rv)) } else { throw PMKError.compactMap(value, U.self) } } catch { rp.box.seal(.rejected(error)) } } case .rejected(let error): rp.box.seal(.rejected(error)) } } return rp } #endif /** The provided closure is executed when this promise is fulfilled. Equivalent to `map { x -> Void in`, but since we force the `Void` return Swift is happier and gives you less hassle about your closure’s qualification. - Parameter on: The queue to which the provided closure dispatches. - Parameter body: The closure that is executed when this Promise is fulfilled. - Returns: A new promise fulfilled as `Void` or rejected if the provided closure throws. firstly { URLSession.shared.dataTask(.promise, with: url) }.done { response in print(response.data) } */ func done(on: DispatchQueue? = conf.Q.return, flags: DispatchWorkItemFlags? = nil, _ body: @escaping(T) throws -> Void) -> Promise { let rp = Promise(.pending) pipe { switch $0 { case .fulfilled(let value): on.async(flags: flags) { do { try body(value) rp.box.seal(.fulfilled(())) } catch { rp.box.seal(.rejected(error)) } } case .rejected(let error): rp.box.seal(.rejected(error)) } } return rp } /** The provided closure is executed when this promise is fulfilled. This is like `done` but it returns the same value that the handler is fed. `get` immutably accesses the fulfilled value; the returned Promise maintains that value. - Parameter on: The queue to which the provided closure dispatches. - Parameter body: The closure that is executed when this Promise is fulfilled. - Returns: A new promise that is fulfilled with the value that the handler is fed or rejected if the provided closure throws. For example: firstly { .value(1) }.get { foo in print(foo, " is 1") }.done { foo in print(foo, " is 1") }.done { foo in print(foo, " is Void") } */ func get(on: DispatchQueue? = conf.Q.return, flags: DispatchWorkItemFlags? = nil, _ body: @escaping (T) throws -> Void) -> Promise { return map(on: on, flags: flags) { try body($0) return $0 } } /** The provided closure is executed with promise result. This is like `get` but provides the Result of the Promise so you can inspect the value of the chain at this point without causing any side effects. - Parameter on: The queue to which the provided closure dispatches. - Parameter body: The closure that is executed with Result of Promise. - Returns: A new promise that is resolved with the result that the handler is fed. For example: promise.tap{ print($0) }.then{ /*…*/ } */ func tap(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, _ body: @escaping(Result) -> Void) -> Promise { return Promise { seal in pipe { result in on.async(flags: flags) { body(result) seal.resolve(result) } } } } /// - Returns: a new promise chained off this promise but with its value discarded. func asVoid() -> Promise { return map(on: nil) { _ in } } } public extension Thenable { /** - Returns: The error with which this promise was rejected; `nil` if this promise is not rejected. */ var error: Error? { switch result { case .none: return nil case .some(.fulfilled): return nil case .some(.rejected(let error)): return error } } /** - Returns: `true` if the promise has not yet resolved. */ var isPending: Bool { return result == nil } /** - Returns: `true` if the promise has resolved. */ var isResolved: Bool { return !isPending } /** - Returns: `true` if the promise was fulfilled. */ var isFulfilled: Bool { return value != nil } /** - Returns: `true` if the promise was rejected. */ var isRejected: Bool { return error != nil } /** - Returns: The value with which this promise was fulfilled or `nil` if this promise is pending or rejected. */ var value: T? { switch result { case .none: return nil case .some(.fulfilled(let value)): return value case .some(.rejected): return nil } } } public extension Thenable where T: Sequence { /** `Promise<[T]>` => `T` -> `U` => `Promise<[U]>` firstly { .value([1,2,3]) }.mapValues { integer in integer * 2 }.done { // $0 => [2,4,6] } */ func mapValues(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, _ transform: @escaping(T.Iterator.Element) throws -> U) -> Promise<[U]> { return map(on: on, flags: flags){ try $0.map(transform) } } #if swift(>=4) && !swift(>=5.2) /** `Promise<[T]>` => `KeyPath` => `Promise<[U]>` firstly { .value([Person(name: "Max"), Person(name: "Roman"), Person(name: "John")]) }.mapValues(\.name).done { // $0 => ["Max", "Roman", "John"] } */ func mapValues(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, _ keyPath: KeyPath) -> Promise<[U]> { return map(on: on, flags: flags){ $0.map { $0[keyPath: keyPath] } } } #endif /** `Promise<[T]>` => `T` -> `[U]` => `Promise<[U]>` firstly { .value([1,2,3]) }.flatMapValues { integer in [integer, integer] }.done { // $0 => [1,1,2,2,3,3] } */ func flatMapValues(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, _ transform: @escaping(T.Iterator.Element) throws -> U) -> Promise<[U.Iterator.Element]> { return map(on: on, flags: flags){ (foo: T) in try foo.flatMap{ try transform($0) } } } /** `Promise<[T]>` => `T` -> `U?` => `Promise<[U]>` firstly { .value(["1","2","a","3"]) }.compactMapValues { Int($0) }.done { // $0 => [1,2,3] } */ func compactMapValues(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, _ transform: @escaping(T.Iterator.Element) throws -> U?) -> Promise<[U]> { return map(on: on, flags: flags) { foo -> [U] in #if !swift(>=3.3) || (swift(>=4) && !swift(>=4.1)) return try foo.flatMap(transform) #else return try foo.compactMap(transform) #endif } } #if swift(>=4) && !swift(>=5.2) /** `Promise<[T]>` => `KeyPath` => `Promise<[U]>` firstly { .value([Person(name: "Max"), Person(name: "Roman", age: 26), Person(name: "John", age: 23)]) }.compactMapValues(\.age).done { // $0 => [26, 23] } */ func compactMapValues(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, _ keyPath: KeyPath) -> Promise<[U]> { return map(on: on, flags: flags) { foo -> [U] in #if !swift(>=4.1) return foo.flatMap { $0[keyPath: keyPath] } #else return foo.compactMap { $0[keyPath: keyPath] } #endif } } #endif /** `Promise<[T]>` => `T` -> `Promise` => `Promise<[U]>` firstly { .value([1,2,3]) }.thenMap { integer in .value(integer * 2) }.done { // $0 => [2,4,6] } */ func thenMap(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, _ transform: @escaping(T.Iterator.Element) throws -> U) -> Promise<[U.T]> { return then(on: on, flags: flags) { when(fulfilled: try $0.map(transform)) } } /** `Promise<[T]>` => `T` -> `Promise<[U]>` => `Promise<[U]>` firstly { .value([1,2,3]) }.thenFlatMap { integer in .value([integer, integer]) }.done { // $0 => [1,1,2,2,3,3] } */ func thenFlatMap(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, _ transform: @escaping(T.Iterator.Element) throws -> U) -> Promise<[U.T.Iterator.Element]> where U.T: Sequence { return then(on: on, flags: flags) { when(fulfilled: try $0.map(transform)) }.map(on: nil) { $0.flatMap{ $0 } } } /** `Promise<[T]>` => `T` -> Bool => `Promise<[T]>` firstly { .value([1,2,3]) }.filterValues { $0 > 1 }.done { // $0 => [2,3] } */ func filterValues(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, _ isIncluded: @escaping (T.Iterator.Element) -> Bool) -> Promise<[T.Iterator.Element]> { return map(on: on, flags: flags) { $0.filter(isIncluded) } } #if swift(>=4) && !swift(>=5.2) /** `Promise<[T]>` => `KeyPath` => `Promise<[T]>` firstly { .value([Person(name: "Max"), Person(name: "Roman", age: 26, isStudent: false), Person(name: "John", age: 23, isStudent: true)]) }.filterValues(\.isStudent).done { // $0 => [Person(name: "John", age: 23, isStudent: true)] } */ func filterValues(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, _ keyPath: KeyPath) -> Promise<[T.Iterator.Element]> { return map(on: on, flags: flags) { $0.filter { $0[keyPath: keyPath] } } } #endif } public extension Thenable where T: Collection { /// - Returns: a promise fulfilled with the first value of this `Collection` or, if empty, a promise rejected with PMKError.emptySequence. var firstValue: Promise { return map(on: nil) { aa in if let a1 = aa.first { return a1 } else { throw PMKError.emptySequence } } } func firstValue(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, where test: @escaping (T.Iterator.Element) -> Bool) -> Promise { return map(on: on, flags: flags) { for x in $0 where test(x) { return x } throw PMKError.emptySequence } } /// - Returns: a promise fulfilled with the last value of this `Collection` or, if empty, a promise rejected with PMKError.emptySequence. var lastValue: Promise { return map(on: nil) { aa in if aa.isEmpty { throw PMKError.emptySequence } else { let i = aa.index(aa.endIndex, offsetBy: -1) return aa[i] } } } } public extension Thenable where T: Sequence, T.Iterator.Element: Comparable { /// - Returns: a promise fulfilled with the sorted values of this `Sequence`. func sortedValues(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil) -> Promise<[T.Iterator.Element]> { return map(on: on, flags: flags){ $0.sorted() } } } ================================================ FILE: Sources/after.m ================================================ #import "AnyPromise.h" @import Dispatch; @import Foundation.NSDate; @import Foundation.NSValue; /// @return A promise that fulfills after the specified duration. AnyPromise *PMKAfter(NSTimeInterval duration) { return [AnyPromise promiseWithResolverBlock:^(PMKResolver resolve) { dispatch_time_t time = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(duration * NSEC_PER_SEC)); dispatch_after(time, dispatch_get_global_queue(QOS_CLASS_UNSPECIFIED, 0), ^{ resolve(@(duration)); }); }]; } ================================================ FILE: Sources/after.swift ================================================ import struct Foundation.TimeInterval import Dispatch /** after(seconds: 1.5).then { //… } - Returns: A guarantee that resolves after the specified duration. */ public func after(seconds: TimeInterval) -> Guarantee { let (rg, seal) = Guarantee.pending() let when = DispatchTime.now() + seconds #if swift(>=4.0) q.asyncAfter(deadline: when) { seal(()) } #else q.asyncAfter(deadline: when, execute: seal) #endif return rg } /** after(.seconds(2)).then { //… } - Returns: A guarantee that resolves after the specified duration. */ public func after(_ interval: DispatchTimeInterval) -> Guarantee { let (rg, seal) = Guarantee.pending() let when = DispatchTime.now() + interval #if swift(>=4.0) q.asyncAfter(deadline: when) { seal(()) } #else q.asyncAfter(deadline: when, execute: seal) #endif return rg } private var q: DispatchQueue { if #available(macOS 10.10, iOS 8.0, tvOS 9.0, watchOS 2.0, *) { return DispatchQueue.global(qos: .default) } else { return DispatchQueue.global(priority: .default) } } ================================================ FILE: Sources/dispatch_promise.m ================================================ #import "AnyPromise.h" @import Dispatch; AnyPromise *dispatch_promise_on(dispatch_queue_t queue, id block) { return [AnyPromise promiseWithValue:nil].thenOn(queue, block); } AnyPromise *dispatch_promise(id block) { return dispatch_promise_on(dispatch_get_global_queue(QOS_CLASS_UNSPECIFIED, 0), block); } ================================================ FILE: Sources/firstly.swift ================================================ import Dispatch /** Judicious use of `firstly` *may* make chains more readable. Compare: URLSession.shared.dataTask(url: url1).then { URLSession.shared.dataTask(url: url2) }.then { URLSession.shared.dataTask(url: url3) } With: firstly { URLSession.shared.dataTask(url: url1) }.then { URLSession.shared.dataTask(url: url2) }.then { URLSession.shared.dataTask(url: url3) } - Note: the block you pass executes immediately on the current thread/queue. */ public func firstly(execute body: () throws -> U) -> Promise { do { let rp = Promise(.pending) try body().pipe(to: rp.box.seal) return rp } catch { return Promise(error: error) } } /// - See: firstly() public func firstly(execute body: () -> Guarantee) -> Guarantee { return body() } ================================================ FILE: Sources/fwd.h ================================================ #import #import @class AnyPromise; extern NSString * __nonnull const PMKErrorDomain; #define PMKFailingPromiseIndexKey @"PMKFailingPromiseIndexKey" #define PMKJoinPromisesKey @"PMKJoinPromisesKey" #define PMKUnexpectedError 1l #define PMKInvalidUsageError 3l #define PMKAccessDeniedError 4l #define PMKOperationFailed 8l #define PMKTaskError 9l #define PMKJoinError 10l #define PMKNoWinnerError 11l #ifdef __cplusplus extern "C" { #endif /** @return A new promise that resolves after the specified duration. @parameter duration The duration in seconds to wait before this promise is resolve. For example: PMKAfter(1).then(^{ //… }); */ extern AnyPromise * __nonnull PMKAfter(NSTimeInterval duration) NS_REFINED_FOR_SWIFT; /** `when` is a mechanism for waiting more than one asynchronous task and responding when they are all complete. `PMKWhen` accepts varied input. If an array is passed then when those promises fulfill, when’s promise fulfills with an array of fulfillment values. If a dictionary is passed then the same occurs, but when’s promise fulfills with a dictionary of fulfillments keyed as per the input. Interestingly, if a single promise is passed then when waits on that single promise, and if a single non-promise object is passed then when fulfills immediately with that object. If the array or dictionary that is passed contains objects that are not promises, then these objects are considered fulfilled promises. The reason we do this is to allow a pattern know as "abstracting away asynchronicity". If *any* of the provided promises reject, the returned promise is immediately rejected with that promise’s rejection. The error’s `userInfo` object is supplemented with `PMKFailingPromiseIndexKey`. For example: PMKWhen(@[promise1, promise2]).then(^(NSArray *results){ //… }); @warning *Important* In the event of rejection the other promises will continue to resolve and as per any other promise will either fulfill or reject. This is the right pattern for `getter` style asynchronous tasks, but often for `setter` tasks (eg. storing data on a server), you most likely will need to wait on all tasks and then act based on which have succeeded and which have failed. In such situations use `PMKJoin`. @param input The input upon which to wait before resolving this promise. @return A promise that is resolved with either: 1. An array of values from the provided array of promises. 2. The value from the provided promise. 3. The provided non-promise object. @see PMKJoin */ extern AnyPromise * __nonnull PMKWhen(id __nonnull input) NS_REFINED_FOR_SWIFT; /** Creates a new promise that resolves only when all provided promises have resolved. Typically, you should use `PMKWhen`. For example: PMKJoin(@[promise1, promise2]).then(^(NSArray *resultingValues){ //… }).catch(^(NSError *error){ assert(error.domain == PMKErrorDomain); assert(error.code == PMKJoinError); NSArray *promises = error.userInfo[PMKJoinPromisesKey]; for (AnyPromise *promise in promises) { if (promise.rejected) { //… } } }); @param promises An array of promises. @return A promise that thens three parameters: 1) An array of mixed values and errors from the resolved input. 2) An array of values from the promises that fulfilled. 3) An array of errors from the promises that rejected or nil if all promises fulfilled. @see when */ AnyPromise *__nonnull PMKJoin(NSArray * __nonnull promises) NS_REFINED_FOR_SWIFT; /** Literally hangs this thread until the promise has resolved. Do not use hang… unless you are testing, playing or debugging. If you use it in production code I will literally and honestly cry like a child. @return The resolved value of the promise. @warning T SAFE. IT IS NOT SAFE. IT IS NOT SAFE. IT IS NOT SAFE. IT IS NO */ extern id __nullable PMKHang(AnyPromise * __nonnull promise); /** Executes the provided block on a background queue. dispatch_promise is a convenient way to start a promise chain where the first step needs to run synchronously on a background queue. dispatch_promise(^{ return md5(input); }).then(^(NSString *md5){ NSLog(@"md5: %@", md5); }); @param block The block to be executed in the background. Returning an `NSError` will reject the promise, everything else (including void) fulfills the promise. @return A promise resolved with the return value of the provided block. @see dispatch_async */ extern AnyPromise * __nonnull dispatch_promise(id __nonnull block) NS_SWIFT_UNAVAILABLE("Use our `DispatchQueue.async` override instead"); /** Executes the provided block on the specified background queue. dispatch_promise_on(myDispatchQueue, ^{ return md5(input); }).then(^(NSString *md5){ NSLog(@"md5: %@", md5); }); @param block The block to be executed in the background. Returning an `NSError` will reject the promise, everything else (including void) fulfills the promise. @return A promise resolved with the return value of the provided block. @see dispatch_promise */ extern AnyPromise * __nonnull dispatch_promise_on(dispatch_queue_t __nonnull queue, id __nonnull block) NS_SWIFT_UNAVAILABLE("Use our `DispatchQueue.async` override instead"); /** Returns a new promise that resolves when the value of the first resolved promise in the provided array of promises. */ extern AnyPromise * __nonnull PMKRace(NSArray * __nonnull promises) NS_REFINED_FOR_SWIFT; /** Returns a new promise that resolves with the value of the first fulfilled promise in the provided array of promises. */ extern AnyPromise * __nonnull PMKRaceFulfilled(NSArray * __nonnull promises) NS_REFINED_FOR_SWIFT; #ifdef __cplusplus } // Extern C #endif ================================================ FILE: Sources/hang.m ================================================ #import "AnyPromise.h" #import "AnyPromise+Private.h" @import CoreFoundation.CFRunLoop; /** Suspends the active thread waiting on the provided promise. @return The value of the provided promise once resolved. */ id PMKHang(AnyPromise *promise) { if (promise.pending) { static CFRunLoopSourceContext context; CFRunLoopRef runLoop = CFRunLoopGetCurrent(); CFRunLoopSourceRef runLoopSource = CFRunLoopSourceCreate(NULL, 0, &context); CFRunLoopAddSource(runLoop, runLoopSource, kCFRunLoopDefaultMode); promise.ensure(^{ CFRunLoopStop(runLoop); }); while (promise.pending) { CFRunLoopRun(); } CFRunLoopRemoveSource(runLoop, runLoopSource, kCFRunLoopDefaultMode); CFRelease(runLoopSource); } return promise.value; } ================================================ FILE: Sources/hang.swift ================================================ import Foundation import CoreFoundation /** Runs the active run-loop until the provided promise resolves. This is for debug and is not a generally safe function to use in your applications. We mostly provide it for use in testing environments. Still if you like, study how it works (by reading the sources!) and use at your own risk. - Returns: The value of the resolved promise - Throws: An error, should the promise be rejected - See: `wait()` */ public func hang(_ promise: Promise) throws -> T { #if os(Linux) || os(Android) #if swift(>=4) let runLoopMode: CFRunLoopMode = kCFRunLoopDefaultMode #else // isMainThread is not yet implemented on Linux. let runLoopModeRaw = RunLoopMode.defaultRunLoopMode.rawValue._bridgeToObjectiveC() let runLoopMode: CFString = unsafeBitCast(runLoopModeRaw, to: CFString.self) #endif #else guard Thread.isMainThread else { // hang doesn't make sense on threads that aren't the main thread. // use `.wait()` on those threads. fatalError("Only call hang() on the main thread.") } let runLoopMode: CFRunLoopMode = CFRunLoopMode.defaultMode #endif if promise.isPending { var context = CFRunLoopSourceContext() let runLoop = CFRunLoopGetCurrent() let runLoopSource = CFRunLoopSourceCreate(nil, 0, &context) CFRunLoopAddSource(runLoop, runLoopSource, runLoopMode) _ = promise.ensure { CFRunLoopStop(runLoop) } while promise.isPending { CFRunLoopRun() } CFRunLoopRemoveSource(runLoop, runLoopSource, runLoopMode) } switch promise.result! { case .rejected(let error): throw error case .fulfilled(let value): return value } } ================================================ FILE: Sources/join.m ================================================ @import Foundation.NSDictionary; #import "AnyPromise+Private.h" #import @import Foundation.NSError; @import Foundation.NSNull; #import "PromiseKit.h" #import /** Waits on all provided promises. `PMKWhen` rejects as soon as one of the provided promises rejects. `PMKJoin` waits on all provided promises, then rejects if any of those promises rejects, otherwise it fulfills with values from the provided promises. - Returns: A new promise that resolves once all the provided promises resolve. */ AnyPromise *PMKJoin(NSArray *promises) { if (promises == nil) return [AnyPromise promiseWithValue:[NSError errorWithDomain:PMKErrorDomain code:PMKInvalidUsageError userInfo:@{NSLocalizedDescriptionKey: @"PMKJoin(nil)"}]]; if (promises.count == 0) return [AnyPromise promiseWithValue:promises]; return [AnyPromise promiseWithResolverBlock:^(PMKResolver resolve) { NSPointerArray *results = NSPointerArrayMake(promises.count); __block atomic_int countdown = promises.count; __block BOOL rejected = NO; [promises enumerateObjectsUsingBlock:^(AnyPromise *promise, NSUInteger ii, BOOL *stop) { [promise __pipe:^(id value) { if (IsError(value)) { rejected = YES; } //FIXME surely this isn't thread safe on multiple cores? [results replacePointerAtIndex:ii withPointer:(__bridge void *)(value ?: [NSNull null])]; atomic_fetch_sub_explicit(&countdown, 1, memory_order_relaxed); if (countdown == 0) { if (!rejected) { resolve(results.allObjects); } else { id userInfo = @{PMKJoinPromisesKey: promises}; id err = [NSError errorWithDomain:PMKErrorDomain code:PMKJoinError userInfo:userInfo]; resolve(err); } } }]; (void) stop; }]; }]; } ================================================ FILE: Sources/race.m ================================================ #import "AnyPromise+Private.h" #import #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" // ^^ OSAtomicDecrement32 is deprecated on watchOS AnyPromise *PMKRace(NSArray *promises) { if (promises == nil || promises.count == 0) return [AnyPromise promiseWithValue:[NSError errorWithDomain:PMKErrorDomain code:PMKInvalidUsageError userInfo:@{NSLocalizedDescriptionKey: @"PMKRace(nil)"}]]; return [AnyPromise promiseWithResolverBlock:^(PMKResolver resolve) { for (AnyPromise *promise in promises) { [promise __pipe:resolve]; } }]; } /** Waits for one promise to fulfill @note If there are no fulfilled promises, the returned promise is rejected with `PMKNoWinnerError`. @param promises The promises to fulfill. @return The promise that was fulfilled first. */ AnyPromise *PMKRaceFulfilled(NSArray *promises) { if (promises == nil || promises.count == 0) return [AnyPromise promiseWithValue:[NSError errorWithDomain:PMKErrorDomain code:PMKInvalidUsageError userInfo:@{NSLocalizedDescriptionKey: @"PMKRaceFulfilled(nil)"}]]; __block int32_t countdown = (int32_t)[promises count]; return [AnyPromise promiseWithResolverBlock:^(PMKResolver resolve) { for (__strong AnyPromise* promise in promises) { [promise __pipe:^(id value) { if (IsError(value)) { if (OSAtomicDecrement32(&countdown) == 0) { id err = [NSError errorWithDomain:PMKErrorDomain code:PMKNoWinnerError userInfo:@{NSLocalizedDescriptionKey: @"PMKRaceFulfilled(nil)"}]; resolve(err); } } else { resolve(value); } }]; } }]; } #pragma GCC diagnostic pop ================================================ FILE: Sources/race.swift ================================================ import Dispatch @inline(__always) private func _race(_ thenables: [U]) -> Promise { let rp = Promise(.pending) for thenable in thenables { thenable.pipe(to: rp.box.seal) } return rp } /** Waits for one promise to resolve race(promise1, promise2, promise3).then { winner in //… } - Returns: The promise that resolves first - Warning: If the first resolution is a rejection, the returned promise is rejected */ public func race(_ thenables: U...) -> Promise { return _race(thenables) } /** Waits for one promise to resolve race(promise1, promise2, promise3).then { winner in //… } - Returns: The promise that resolves first - Warning: If the first resolution is a rejection, the returned promise is rejected - Remark: If the provided array is empty the returned promise is rejected with PMKError.badInput */ public func race(_ thenables: [U]) -> Promise { guard !thenables.isEmpty else { return Promise(error: PMKError.badInput) } return _race(thenables) } /** Waits for one guarantee to resolve race(promise1, promise2, promise3).then { winner in //… } - Returns: The guarantee that resolves first */ public func race(_ guarantees: Guarantee...) -> Guarantee { let rg = Guarantee(.pending) for guarantee in guarantees { guarantee.pipe(to: rg.box.seal) } return rg } /** Waits for one promise to fulfill race(fulfilled: [promise1, promise2, promise3]).then { winner in //… } - Returns: The promise that was fulfilled first. - Warning: Skips all rejected promises. - Remark: If the provided array is empty, the returned promise is rejected with `PMKError.badInput`. If there are no fulfilled promises, the returned promise is rejected with `PMKError.noWinner`. */ public func race(fulfilled thenables: [U]) -> Promise { var countdown = thenables.count guard countdown > 0 else { return Promise(error: PMKError.badInput) } let rp = Promise(.pending) let barrier = DispatchQueue(label: "org.promisekit.barrier.race", attributes: .concurrent) for promise in thenables { promise.pipe { result in barrier.sync(flags: .barrier) { switch result { case .rejected: guard rp.isPending else { return } countdown -= 1 if countdown == 0 { rp.box.seal(.rejected(PMKError.noWinner)) } case .fulfilled(let value): guard rp.isPending else { return } countdown = 0 rp.box.seal(.fulfilled(value)) } } } } return rp } ================================================ FILE: Sources/when.m ================================================ @import Foundation.NSDictionary; #import "AnyPromise+Private.h" @import Foundation.NSProgress; #import @import Foundation.NSError; @import Foundation.NSNull; #import "PromiseKit.h" #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" // ^^ OSAtomicDecrement32 is deprecated on watchOS // NSProgress resources: // * https://robots.thoughtbot.com/asynchronous-nsprogress // * http://oleb.net/blog/2014/03/nsprogress/ // NSProgress! Beware! // * https://github.com/AFNetworking/AFNetworking/issues/2261 /** Wait for all promises in a set to resolve. @note If *any* of the provided promises reject, the returned promise is immediately rejected with that error. @warning In the event of rejection the other promises will continue to resolve and, as per any other promise, will either fulfill or reject. This is the right pattern for `getter` style asynchronous tasks, but often for `setter` tasks (eg. storing data on a server), you most likely will need to wait on all tasks and then act based on which have succeeded and which have failed, in such situations use `when(resolved:)`. @param promises The promises upon which to wait before the returned promise resolves. @note PMKWhen provides NSProgress. @return A new promise that resolves when all the provided promises fulfill or one of the provided promises rejects. */ AnyPromise *PMKWhen(id promises) { if (promises == nil) return [AnyPromise promiseWithValue:[NSError errorWithDomain:PMKErrorDomain code:PMKInvalidUsageError userInfo:@{NSLocalizedDescriptionKey: @"PMKWhen(nil)"}]]; if ([promises isKindOfClass:[NSArray class]] || [promises isKindOfClass:[NSDictionary class]]) { if ([promises count] == 0) return [AnyPromise promiseWithValue:promises]; } else if ([promises isKindOfClass:[AnyPromise class]]) { promises = @[promises]; } else { return [AnyPromise promiseWithValue:promises]; } #ifndef PMKDisableProgress NSProgress *progress = [NSProgress progressWithTotalUnitCount:(int64_t)[promises count]]; progress.pausable = NO; progress.cancellable = NO; #else struct PMKProgress { int completedUnitCount; int totalUnitCount; double fractionCompleted; }; __block struct PMKProgress progress; #endif __block int32_t countdown = (int32_t)[promises count]; BOOL const isdict = [promises isKindOfClass:[NSDictionary class]]; return [AnyPromise promiseWithResolverBlock:^(PMKResolver resolve) { NSInteger index = 0; for (__strong id key in promises) { AnyPromise *promise = isdict ? promises[key] : key; if (!isdict) key = @(index); if (![promise isKindOfClass:[AnyPromise class]]) promise = [AnyPromise promiseWithValue:promise]; [promise __pipe:^(id value){ if (progress.fractionCompleted >= 1) return; if (IsError(value)) { progress.completedUnitCount = progress.totalUnitCount; NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithDictionary:[(NSError *)value userInfo] ?: @{}]; userInfo[PMKFailingPromiseIndexKey] = key; [userInfo setObject:value forKey:NSUnderlyingErrorKey]; id err = [[NSError alloc] initWithDomain:[value domain] code:[value code] userInfo:userInfo]; resolve(err); } else if (OSAtomicDecrement32(&countdown) == 0) { progress.completedUnitCount = progress.totalUnitCount; id results; if (isdict) { results = [NSMutableDictionary new]; for (id key in promises) { id promise = promises[key]; results[key] = IsPromise(promise) ? ((AnyPromise *)promise).value : promise; } } else { results = [NSMutableArray new]; for (AnyPromise *promise in promises) { id value = IsPromise(promise) ? (promise.value ?: [NSNull null]) : promise; [results addObject:value]; } } resolve(results); } else { progress.completedUnitCount++; } }]; } }]; } #pragma GCC diagnostic pop ================================================ FILE: Sources/when.swift ================================================ import Foundation import Dispatch private func _when(_ thenables: [U]) -> Promise { var countdown = thenables.count guard countdown > 0 else { return .value(Void()) } let rp = Promise(.pending) #if PMKDisableProgress || os(Linux) var progress: (completedUnitCount: Int, totalUnitCount: Int) = (0, 0) #else let progress = Progress(totalUnitCount: Int64(thenables.count)) progress.isCancellable = false progress.isPausable = false #endif let barrier = DispatchQueue(label: "org.promisekit.barrier.when", attributes: .concurrent) for promise in thenables { promise.pipe { result in barrier.sync(flags: .barrier) { switch result { case .rejected(let error): if rp.isPending { progress.completedUnitCount = progress.totalUnitCount rp.box.seal(.rejected(error)) } case .fulfilled: guard rp.isPending else { return } progress.completedUnitCount += 1 countdown -= 1 if countdown == 0 { rp.box.seal(.fulfilled(())) } } } } } return rp } private func __when(_ guarantees: [Guarantee]) -> Guarantee { var countdown = guarantees.count guard countdown > 0 else { return .value(Void()) } let rg = Guarantee(.pending) #if PMKDisableProgress || os(Linux) var progress: (completedUnitCount: Int, totalUnitCount: Int) = (0, 0) #else let progress = Progress(totalUnitCount: Int64(guarantees.count)) progress.isCancellable = false progress.isPausable = false #endif let barrier = DispatchQueue(label: "org.promisekit.barrier.when", attributes: .concurrent) for guarantee in guarantees { guarantee.pipe { (_: T) in barrier.sync(flags: .barrier) { guard rg.isPending else { return } progress.completedUnitCount += 1 countdown -= 1 if countdown == 0 { rg.box.seal(()) } } } } return rg } /** Wait for all promises in a set to fulfill. For example: when(fulfilled: promise1, promise2).then { results in //… }.catch { error in switch error { case URLError.notConnectedToInternet: //… case CLError.denied: //… } } - Note: If *any* of the provided promises reject, the returned promise is immediately rejected with that error. - Warning: In the event of rejection the other promises will continue to resolve and, as per any other promise, will either fulfill or reject. This is the right pattern for `getter` style asynchronous tasks, but often for `setter` tasks (eg. storing data on a server), you most likely will need to wait on all tasks and then act based on which have succeeded and which have failed, in such situations use `when(resolved:)`. - Parameter promises: The promises upon which to wait before the returned promise resolves. - Returns: A new promise that resolves when all the provided promises fulfill or one of the provided promises rejects. - Note: `when` provides `NSProgress`. - SeeAlso: `when(resolved:)` */ public func when(fulfilled thenables: [U]) -> Promise<[U.T]> { return _when(thenables).map(on: nil) { thenables.map{ $0.value! } } } #if swift(>=5.7) public func when(fulfilled thenables: [any Thenable]) -> Promise<[Any]> { return _when(thenables.map { $0.asVoid()}).map(on: nil) { thenables.map { $0.value! } } } #endif #if swift(>=5.9) public func when(fulfilled: repeat each U) -> Promise<(repeat (each U).T)> { var voidPromises: [Promise] = [] repeat voidPromises.append((each fulfilled).asVoid()) return _when(voidPromises).map(on: nil) { (repeat (each fulfilled).value!) } } #endif /// Wait for all promises in a set to fulfill. public func when(fulfilled promises: U...) -> Promise where U.T == Void { return _when(promises) } /// Wait for all promises in a set to fulfill. public func when(fulfilled promises: [U]) -> Promise where U.T == Void { return _when(promises) } /// Wait for all promises in a set to fulfill. public func when(fulfilled pu: U, _ pv: V) -> Promise<(U.T, V.T)> { return _when([pu.asVoid(), pv.asVoid()]).map(on: nil) { (pu.value!, pv.value!) } } /// Wait for all promises in a set to fulfill. public func when(fulfilled pu: U, _ pv: V, _ pw: W) -> Promise<(U.T, V.T, W.T)> { return _when([pu.asVoid(), pv.asVoid(), pw.asVoid()]).map(on: nil) { (pu.value!, pv.value!, pw.value!) } } /// Wait for all promises in a set to fulfill. public func when(fulfilled pu: U, _ pv: V, _ pw: W, _ px: X) -> Promise<(U.T, V.T, W.T, X.T)> { return _when([pu.asVoid(), pv.asVoid(), pw.asVoid(), px.asVoid()]).map(on: nil) { (pu.value!, pv.value!, pw.value!, px.value!) } } /// Wait for all promises in a set to fulfill. public func when(fulfilled pu: U, _ pv: V, _ pw: W, _ px: X, _ py: Y) -> Promise<(U.T, V.T, W.T, X.T, Y.T)> { return _when([pu.asVoid(), pv.asVoid(), pw.asVoid(), px.asVoid(), py.asVoid()]).map(on: nil) { (pu.value!, pv.value!, pw.value!, px.value!, py.value!) } } /** Generate promises at a limited rate and wait for all to fulfill. For example: func downloadFile(url: URL) -> Promise { // ... } let urls: [URL] = /*…*/ let urlGenerator = urls.makeIterator() let generator = AnyIterator> { guard url = urlGenerator.next() else { return nil } return downloadFile(url) } when(generator, concurrently: 3).done { datas in // ... } No more than three downloads will occur simultaneously. - Note: The generator is called *serially* on a *background* queue. - Warning: Refer to the warnings on `when(fulfilled:)` - Parameter promiseGenerator: Generator of promises. - Returns: A new promise that resolves when all the provided promises fulfill or one of the provided promises rejects. - SeeAlso: `when(resolved:)` */ public func when(fulfilled promiseIterator: It, concurrently: Int) -> Promise<[It.Element.T]> where It.Element: Thenable { guard concurrently > 0 else { return Promise(error: PMKError.badInput) } var generator = promiseIterator let root = Promise<[It.Element.T]>.pending() var pendingPromises = 0 var promises: [It.Element] = [] let barrier = DispatchQueue(label: "org.promisekit.barrier.when", attributes: [.concurrent]) func dequeue() { guard root.promise.isPending else { return } // don’t continue dequeueing if root has been rejected var shouldDequeue = false barrier.sync { shouldDequeue = pendingPromises < concurrently } guard shouldDequeue else { return } var promise: It.Element! barrier.sync(flags: .barrier) { guard let next = generator.next() else { return } promise = next pendingPromises += 1 promises.append(next) } func testDone() { barrier.sync { if pendingPromises == 0 { #if !swift(>=3.3) || (swift(>=4) && !swift(>=4.1)) root.resolver.fulfill(promises.flatMap{ $0.value }) #else root.resolver.fulfill(promises.compactMap{ $0.value }) #endif } } } guard promise != nil else { return testDone() } promise.pipe { resolution in barrier.sync(flags: .barrier) { pendingPromises -= 1 } switch resolution { case .fulfilled: dequeue() testDone() case .rejected(let error): root.resolver.reject(error) } } dequeue() } dequeue() return root.promise } /** Waits on all provided promises. `when(fulfilled:)` rejects as soon as one of the provided promises rejects. `when(resolved:)` waits on all provided promises whatever their result, and then provides an array of `Result` so you can individually inspect the results. As a consequence this function returns a `Guarantee`, ie. errors are lifted from the individual promises into the results array of the returned `Guarantee`. when(resolved: promise1, promise2, promise3).then { results in for result in results where case .fulfilled(let value) { //… } }.catch { error in // invalid! Never rejects } - Returns: A new promise that resolves once all the provided promises resolve. The array is ordered the same as the input, ie. the result order is *not* resolution order. - Note: we do not provide tuple variants for `when(resolved:)` but will accept a pull-request - Remark: Doesn't take Thenable due to protocol `associatedtype` paradox */ public func when(resolved promises: Promise...) -> Guarantee<[Result]> { return when(resolved: promises) } /// - See: `when(resolved: Promise...)` public func when(resolved promises: [Promise]) -> Guarantee<[Result]> { guard !promises.isEmpty else { return .value([]) } var countdown = promises.count let barrier = DispatchQueue(label: "org.promisekit.barrier.join", attributes: .concurrent) let rg = Guarantee<[Result]>(.pending) for promise in promises { promise.pipe { result in barrier.sync(flags: .barrier) { countdown -= 1 } barrier.sync { if countdown == 0 { rg.box.seal(promises.map{ $0.result! }) } } } } return rg } /** Generate promises at a limited rate and wait for all to resolve. For example: func downloadFile(url: URL) -> Promise { // ... } let urls: [URL] = /*…*/ let urlGenerator = urls.makeIterator() let generator = AnyIterator> { guard url = urlGenerator.next() else { return nil } return downloadFile(url) } when(resolved: generator, concurrently: 3).done { results in // ... } No more than three downloads will occur simultaneously. Downloads will continue if one of them fails - Note: The generator is called *serially* on a *background* queue. - Warning: Refer to the warnings on `when(resolved:)` - Parameter promiseGenerator: Generator of promises. - Returns: A new promise that resolves once all the provided promises resolve. The array is ordered the same as the input, ie. the result order is *not* resolution order. - SeeAlso: `when(resolved:)` */ #if swift(>=5.3) public func when(resolved promiseIterator: It, concurrently: Int) -> Guarantee<[Result]> where It.Element: Thenable { guard concurrently > 0 else { return Guarantee.value([Result.rejected(PMKError.badInput)]) } var generator = promiseIterator let root = Guarantee<[Result]>.pending() var pendingPromises = 0 var promises: [It.Element] = [] let barrier = DispatchQueue(label: "org.promisekit.barrier.when", attributes: [.concurrent]) func dequeue() { guard root.guarantee.isPending else { return } // don’t continue dequeueing if root has been rejected var shouldDequeue = false barrier.sync { shouldDequeue = pendingPromises < concurrently } guard shouldDequeue else { return } var promise: It.Element! barrier.sync(flags: .barrier) { guard let next = generator.next() else { return } promise = next pendingPromises += 1 promises.append(next) } func testDone() { barrier.sync { if pendingPromises == 0 { #if !swift(>=3.3) || (swift(>=4) && !swift(>=4.1)) root.resolve(promises.flatMap { $0.result }) #else root.resolve(promises.compactMap { $0.result }) #endif } } } guard promise != nil else { return testDone() } promise.pipe { _ in barrier.sync(flags: .barrier) { pendingPromises -= 1 } dequeue() testDone() } dequeue() } dequeue() return root.guarantee } #endif /// Waits on all provided Guarantees. public func when(_ guarantees: Guarantee...) -> Guarantee { return when(guarantees: guarantees) } /// Waits on all provided Guarantees. public func when(_ guarantees: Guarantee...) -> Guarantee<[T]> { return when(guarantees: guarantees) } /// Waits on all provided Guarantees. public func when(guarantees: [Guarantee]) -> Guarantee { return when(fulfilled: guarantees).recover{ _ in }.asVoid() } /// Waits on all provided Guarantees. public func when(guarantees: [Guarantee]) -> Guarantee<[T]> { return __when(guarantees).map(on: nil) { guarantees.map { $0.value! } } } /// Waits on all provided Guarantees. public func when(guarantees gu: Guarantee, _ gv: Guarantee) -> Guarantee<(U, V)> { return __when([gu.asVoid(), gv.asVoid()]).map(on: nil) { (gu.value!, gv.value!) } } /// Waits on all provided Guarantees. public func when(guarantees gu: Guarantee, _ gv: Guarantee, _ gw: Guarantee) -> Guarantee<(U, V, W)> { return __when([gu.asVoid(), gv.asVoid(), gw.asVoid()]).map(on: nil) { (gu.value!, gv.value!, gw.value!) } } /// Waits on all provided Guarantees. public func when(guarantees gu: Guarantee, _ gv: Guarantee, _ gw: Guarantee, _ gx: Guarantee) -> Guarantee<(U, V, W, X)> { return __when([gu.asVoid(), gv.asVoid(), gw.asVoid(), gx.asVoid()]).map(on: nil) { (gu.value!, gv.value!, gw.value!, gx.value!) } } /// Waits on all provided Guarantees. public func when(guarantees gu: Guarantee, _ gv: Guarantee, _ gw: Guarantee, _ gx: Guarantee, _ gy: Guarantee) -> Guarantee<(U, V, W, X, Y)> { return __when([gu.asVoid(), gv.asVoid(), gw.asVoid(), gx.asVoid(), gy.asVoid()]).map(on: nil) { (gu.value!, gv.value!, gw.value!, gx.value!, gy.value!) } } ================================================ FILE: Tests/A+/0.0.0.swift ================================================ import PromiseKit import Dispatch import XCTest enum Error: Swift.Error { case dummy // we reject with this when we don't intend to test against it case sentinel(UInt32) } private let timeout: TimeInterval = 10 extension XCTestCase { func describe(_ description: String, file: StaticString = #file, line: UInt = #line, body: () throws -> Void) { PromiseKit.conf.Q.map = .main do { try body() } catch { XCTFail(description, file: file, line: line) } } func specify(_ description: String, file: StaticString = #file, line: UInt = #line, body: ((promise: Promise, fulfill: () -> Void, reject: (Error) -> Void), XCTestExpectation) throws -> Void) { let expectation = self.expectation(description: description) let (pending, seal) = Promise.pending() do { try body((pending, seal.fulfill_, seal.reject), expectation) waitForExpectations(timeout: timeout) { err in if let _ = err { XCTFail("wait failed: \(description)", file: file, line: line) } } } catch { XCTFail(description, file: file, line: line) } } func testFulfilled(file: StaticString = #file, line: UInt = #line, body: @escaping (Promise, XCTestExpectation, UInt32) -> Void) { testFulfilled(withExpectationCount: 1, file: file, line: line) { body($0, $1.first!, $2) } } func testRejected(file: StaticString = #file, line: UInt = #line, body: @escaping (Promise, XCTestExpectation, UInt32) -> Void) { testRejected(withExpectationCount: 1, file: file, line: line) { body($0, $1.first!, $2) } } func testFulfilled(withExpectationCount: Int, file: StaticString = #file, line: UInt = #line, body: @escaping (Promise, [XCTestExpectation], UInt32) -> Void) { let specify = mkspecify(withExpectationCount, file: file, line: line, body: body) specify("already-fulfilled") { value in return (.value(value), {}) } specify("immediately-fulfilled") { value in let (promise, seal) = Promise.pending() return (promise, { seal.fulfill(value) }) } specify("eventually-fulfilled") { value in let (promise, seal) = Promise.pending() return (promise, { after(ticks: 5) { seal.fulfill(value) } }) } } func testRejected(withExpectationCount: Int, file: StaticString = #file, line: UInt = #line, body: @escaping (Promise, [XCTestExpectation], UInt32) -> Void) { let specify = mkspecify(withExpectationCount, file: file, line: line, body: body) specify("already-rejected") { sentinel in return (Promise(error: Error.sentinel(sentinel)), {}) } specify("immediately-rejected") { sentinel in let (promise, seal) = Promise.pending() return (promise, { seal.reject(Error.sentinel(sentinel)) }) } specify("eventually-rejected") { sentinel in let (promise, seal) = Promise.pending() return (promise, { after(ticks: 50) { seal.reject(Error.sentinel(sentinel)) } }) } } ///////////////////////////////////////////////////////////////////////// private func mkspecify(_ numberOfExpectations: Int, file: StaticString, line: UInt, body: @escaping (Promise, [XCTestExpectation], UInt32) -> Void) -> (String, _ feed: (UInt32) -> (Promise, () -> Void)) -> Void { return { desc, feed in let value = arc4random() let (promise, executeAfter) = feed(value) let expectations = (1...numberOfExpectations).map { self.expectation(description: "\(desc) (\($0))") } body(promise, expectations, value) executeAfter() self.waitForExpectations(timeout: timeout) { err in if let _ = err { XCTFail("timed out: \(desc)", file: file, line: line) } } } } func mkex() -> XCTestExpectation { return expectation(description: "") } } func after(ticks: Int, execute body: @escaping () -> Void) { precondition(ticks > 0) var ticks = ticks func f() { DispatchQueue.main.async { ticks -= 1 if ticks == 0 { body() } else { f() } } } f() } extension Promise { func test(onFulfilled: @escaping () -> Void, onRejected: @escaping () -> Void) { tap { result in switch result { case .fulfilled: onFulfilled() case .rejected: onRejected() } }.silenceWarning() } } prefix func ++(a: inout Int) -> Int { a += 1 return a } extension Promise { func silenceWarning() {} } #if os(Linux) import func Glibc.random func arc4random() -> UInt32 { return UInt32(random()) } extension XCTestExpectation { func fulfill() { fulfill(#file, line: #line) } } extension XCTestCase { func wait(for: [XCTestExpectation], timeout: TimeInterval, file: StaticString = #file, line: UInt = #line) { #if !(swift(>=4.0) && !swift(>=4.1)) let line = Int(line) #endif waitForExpectations(timeout: timeout, file: file, line: line) } } #endif ================================================ FILE: Tests/A+/2.1.2.swift ================================================ import PromiseKit import XCTest class Test212: XCTestCase { func test() { describe("2.1.2.1: When fulfilled, a promise: must not transition to any other state.") { testFulfilled { promise, expectation, _ in promise.test(onFulfilled: expectation.fulfill, onRejected: { XCTFail() }) } specify("trying to fulfill then immediately reject") { d, expectation in d.promise.test(onFulfilled: expectation.fulfill, onRejected: { XCTFail() }) d.fulfill() d.reject(Error.dummy) } specify("trying to fulfill then reject, delayed") { d, expectation in d.promise.test(onFulfilled: expectation.fulfill, onRejected: { XCTFail() }) after(ticks: 1) { d.fulfill() d.reject(Error.dummy) } } } } } ================================================ FILE: Tests/A+/2.1.3.swift ================================================ import PromiseKit import XCTest class Test213: XCTestCase { func test() { describe("2.1.3.1: When rejected, a promise: must not transition to any other state.") { testRejected { promise, expectation, _ in promise.test(onFulfilled: { XCTFail() }, onRejected: expectation.fulfill) } specify("trying to reject then immediately fulfill") { d, expectation in d.promise.test(onFulfilled: { XCTFail() }, onRejected: expectation.fulfill) d.reject(Error.dummy) d.fulfill() } specify("trying to reject then fulfill, delayed") { d, expectation in d.promise.test(onFulfilled: { XCTFail() }, onRejected: expectation.fulfill) after(ticks: 1) { d.reject(Error.dummy) d.fulfill() } } specify("trying to reject immediately then fulfill delayed") { d, expectation in d.promise.test(onFulfilled: { XCTFail() }, onRejected: expectation.fulfill) d.reject(Error.dummy) after(ticks: 1) { d.fulfill() } } } } } ================================================ FILE: Tests/A+/2.2.2.swift ================================================ import PromiseKit import XCTest class Test222: XCTestCase { func test() { describe("2.2.2: If `onFulfilled` is a function,") { describe("2.2.2.1: it must be called after `promise` is fulfilled, with `promise`’s fulfillment value as its first argument.") { testFulfilled { promise, expectation, sentinel in promise.done { XCTAssertEqual(sentinel, $0) expectation.fulfill() }.silenceWarning() } } describe("2.2.2.2: it must not be called before `promise` is fulfilled") { specify("fulfilled after a delay") { d, expectation in var called = false d.promise.done { called = true expectation.fulfill() }.silenceWarning() after(ticks: 5) { XCTAssertFalse(called) d.fulfill() } } specify("never fulfilled") { d, expectation in d.promise.done{ XCTFail() }.silenceWarning() after(ticks: 1000, execute: expectation.fulfill) } } describe("2.2.2.3: it must not be called more than once.") { specify("already-fulfilled") { _, expectation in let ex = (expectation, mkex()) Promise().done { ex.0.fulfill() }.silenceWarning() after(ticks: 1000) { ex.1.fulfill() } } specify("trying to fulfill a pending promise more than once, immediately") { d, expectation in d.promise.done(expectation.fulfill).silenceWarning() d.fulfill() d.fulfill() } specify("trying to fulfill a pending promise more than once, delayed") { d, expectation in d.promise.done(expectation.fulfill).silenceWarning() after(ticks: 5) { d.fulfill() d.fulfill() } } specify("trying to fulfill a pending promise more than once, immediately then delayed") { d, expectation in let ex = (expectation, mkex()) d.promise.done(ex.0.fulfill).silenceWarning() d.fulfill() after(ticks: 5) { d.fulfill() } after(ticks: 10, execute: ex.1.fulfill) } specify("when multiple `then` calls are made, spaced apart in time") { d, expectation in let ex = (expectation, self.expectation(description: ""), self.expectation(description: ""), self.expectation(description: "")) do { d.promise.done(ex.0.fulfill).silenceWarning() } after(ticks: 5) { d.promise.done(ex.1.fulfill).silenceWarning() } after(ticks: 10) { d.promise.done(ex.2.fulfill).silenceWarning() } after(ticks: 15) { d.fulfill() ex.3.fulfill() } } specify("when `then` is interleaved with fulfillment") { d, expectation in let ex = (expectation, self.expectation(description: ""), self) d.promise.done(ex.0.fulfill).silenceWarning() d.fulfill() d.promise.done(ex.1.fulfill).silenceWarning() } } } } } ================================================ FILE: Tests/A+/2.2.3.swift ================================================ import PromiseKit import XCTest class Test223: XCTestCase { func test() { describe("2.2.3: If `onRejected` is a function,") { describe("2.2.3.1: it must be called after `promise` is rejected, with `promise`’s rejection reason as its first argument.") { testRejected { promise, expectation, sentinel in promise.catch { error in if case Error.sentinel(let value) = error { XCTAssertEqual(value, sentinel) } else { XCTFail() } expectation.fulfill() } } } describe("2.2.3.2: it must not be called before `promise` is rejected") { specify("rejected after a delay") { d, expectation in var called = false d.promise.catch { _ in called = true expectation.fulfill() } after(ticks: 1) { XCTAssertFalse(called) d.reject(Error.dummy) } } specify("never rejected") { d, expectation in d.promise.catch { _ in XCTFail() } after(ticks: 1, execute: expectation.fulfill) } } describe("2.2.3.3: it must not be called more than once.") { specify("already-rejected") { d, expectation in var timesCalled = 0 Promise(error: Error.dummy).catch { _ in XCTAssertEqual(++timesCalled, 1) } after(ticks: 2) { XCTAssertEqual(timesCalled, 1) expectation.fulfill() } } specify("trying to reject a pending promise more than once, immediately") { d, expectation in d.promise.catch{_ in expectation.fulfill() } d.reject(Error.dummy) d.reject(Error.dummy) } specify("trying to reject a pending promise more than once, delayed") { d, expectation in d.promise.catch{_ in expectation.fulfill() } after(ticks: 1) { d.reject(Error.dummy) d.reject(Error.dummy) } } specify("trying to reject a pending promise more than once, immediately then delayed") { d, expectation in d.promise.catch{_ in expectation.fulfill() } d.reject(Error.dummy) after(ticks: 1) { d.reject(Error.dummy) } } specify("when multiple `then` calls are made, spaced apart in time") { d, expectation in let mk = { self.expectation(description: "") } let ex = (expectation, mk(), mk(), mk()) do { d.promise.catch{ _ in ex.0.fulfill() } } after(ticks: 1) { d.promise.catch{ _ in ex.1.fulfill() } } after(ticks: 2) { d.promise.catch{ _ in ex.2.fulfill() } } after(ticks: 3) { d.reject(Error.dummy) ex.3.fulfill() } } specify("when `then` is interleaved with rejection") { d, expectation in let ex = (expectation, self.expectation(description: "")) d.promise.catch{ _ in ex.0.fulfill() } d.reject(Error.dummy) d.promise.catch{ _ in ex.1.fulfill() } } } } } } ================================================ FILE: Tests/A+/2.2.4.swift ================================================ import PromiseKit import XCTest class Test224: XCTestCase { func test() { describe("2.2.4: `onFulfilled` or `onRejected` must not be called until the execution context stack contains only platform code.") { describe("`then` returns before the promise becomes fulfilled or rejected") { testFulfilled { promise, expectation, dummy in var thenHasReturned = false promise.done { _ in XCTAssert(thenHasReturned) expectation.fulfill() }.silenceWarning() thenHasReturned = true } testRejected { promise, expectation, memo in var catchHasReturned = false promise.catch { _->() in XCTAssert(catchHasReturned) expectation.fulfill() } catchHasReturned = true } } describe("Clean-stack execution ordering tests (fulfillment case)") { specify("when `onFulfilled` is added immediately before the promise is fulfilled") { d, expectation in var onFulfilledCalled = false d.promise.done { onFulfilledCalled = true expectation.fulfill() }.silenceWarning() d.fulfill() XCTAssertFalse(onFulfilledCalled) } specify("when `onFulfilled` is added immediately after the promise is fulfilled") { d, expectation in var onFulfilledCalled = false d.fulfill() d.promise.done { onFulfilledCalled = true expectation.fulfill() }.silenceWarning() XCTAssertFalse(onFulfilledCalled) } specify("when one `onFulfilled` is added inside another `onFulfilled`") { _, expectation in var firstOnFulfilledFinished = false let promise = Promise() promise.done { promise.done { XCTAssertTrue(firstOnFulfilledFinished) expectation.fulfill() }.silenceWarning() firstOnFulfilledFinished = true }.silenceWarning() } specify("when `onFulfilled` is added inside an `onRejected`") { _, expectation in let promise1 = Promise(error: Error.dummy) let promise2 = Promise() var firstOnRejectedFinished = false promise1.catch { _ in promise2.done { XCTAssertTrue(firstOnRejectedFinished) expectation.fulfill() }.silenceWarning() firstOnRejectedFinished = true } } specify("when the promise is fulfilled asynchronously") { d, expectation in var firstStackFinished = false after(ticks: 1) { d.fulfill() firstStackFinished = true } d.promise.done { XCTAssertTrue(firstStackFinished) expectation.fulfill() }.silenceWarning() } } describe("Clean-stack execution ordering tests (rejection case)") { specify("when `onRejected` is added immediately before the promise is rejected") { d, expectation in var onRejectedCalled = false d.promise.catch { _ in onRejectedCalled = true expectation.fulfill() } d.reject(Error.dummy) XCTAssertFalse(onRejectedCalled) } specify("when `onRejected` is added immediately after the promise is rejected") { d, expectation in var onRejectedCalled = false d.reject(Error.dummy) d.promise.catch { _ in onRejectedCalled = true expectation.fulfill() } XCTAssertFalse(onRejectedCalled) } specify("when `onRejected` is added inside an `onFulfilled`") { d, expectation in let promise1 = Promise() let promise2 = Promise(error: Error.dummy) var firstOnFulfilledFinished = false promise1.done { _ in promise2.catch { _ in XCTAssertTrue(firstOnFulfilledFinished) expectation.fulfill() } firstOnFulfilledFinished = true }.silenceWarning() } specify("when one `onRejected` is added inside another `onRejected`") { d, expectation in let promise = Promise(error: Error.dummy) var firstOnRejectedFinished = false; promise.catch { _ in promise.catch { _ in XCTAssertTrue(firstOnRejectedFinished) expectation.fulfill() } firstOnRejectedFinished = true } } specify("when the promise is rejected asynchronously") { d, expectation in var firstStackFinished = false after(ticks: 1) { d.reject(Error.dummy) firstStackFinished = true } d.promise.catch { _ in XCTAssertTrue(firstStackFinished) expectation.fulfill() } } } } } } ================================================ FILE: Tests/A+/2.2.6.swift ================================================ import PromiseKit import XCTest class Test226: XCTestCase { func test() { describe("2.2.6: `then` may be called multiple times on the same promise.") { describe("2.2.6.1: If/when `promise` is fulfilled, all respective `onFulfilled` callbacks must execute in the order of their originating calls to `then`.") { describe("multiple boring fulfillment handlers") { testFulfilled(withExpectationCount: 4) { promise, exes, sentinel -> Void in var orderValidator = 0 promise.done { XCTAssertEqual($0, sentinel) XCTAssertEqual(++orderValidator, 1) exes[0].fulfill() }.silenceWarning() promise.catch { _ in XCTFail() } promise.done { XCTAssertEqual($0, sentinel) XCTAssertEqual(++orderValidator, 2) exes[1].fulfill() }.silenceWarning() promise.catch { _ in XCTFail() } promise.done { XCTAssertEqual($0, sentinel) XCTAssertEqual(++orderValidator, 3) exes[2].fulfill() }.silenceWarning() promise.catch { _ in XCTFail() } promise.done { XCTAssertEqual($0, sentinel) XCTAssertEqual(++orderValidator, 4) exes[3].fulfill() }.silenceWarning() } } describe("multiple fulfillment handlers, one of which throws") { testFulfilled(withExpectationCount: 4) { promise, exes, sentinel in var orderValidator = 0 promise.done { XCTAssertEqual($0, sentinel) XCTAssertEqual(++orderValidator, 1) exes[0].fulfill() }.silenceWarning() promise.catch { _ in XCTFail() } promise.done { XCTAssertEqual($0, sentinel) XCTAssertEqual(++orderValidator, 2) exes[1].fulfill() }.silenceWarning() promise.catch { _ in XCTFail() } promise.done { XCTAssertEqual($0, sentinel) XCTAssertEqual(++orderValidator, 3) exes[2].fulfill() throw Error.dummy }.silenceWarning() promise.catch { value in XCTFail() } promise.done { XCTAssertEqual($0, sentinel) XCTAssertEqual(++orderValidator, 4) exes[3].fulfill() }.silenceWarning() } } describe("results in multiple branching chains with their own fulfillment values") { testFulfilled(withExpectationCount: 3) { promise, exes, memo in let sentinel1 = 671 let sentinel2: UInt32 = 672 let sentinel3 = 673 promise.map { _ in return sentinel1 }.done { value in XCTAssertEqual(sentinel1, value) exes[0].fulfill() }.silenceWarning() promise.done { _ in throw Error.sentinel(sentinel2) }.catch { err in switch err { case Error.sentinel(let err) where err == sentinel2: break default: XCTFail() } exes[1].fulfill() } promise.map { _ in sentinel3 }.done { XCTAssertEqual($0, sentinel3) exes[2].fulfill() }.silenceWarning() } } describe("`onFulfilled` handlers are called in the original order") { testFulfilled(withExpectationCount: 3) { promise, exes, memo in var orderValidator = 0 promise.done { _ in XCTAssertEqual(++orderValidator, 1) exes[0].fulfill() }.silenceWarning() promise.done { _ in XCTAssertEqual(++orderValidator, 2) exes[1].fulfill() }.silenceWarning() promise.done { _ in XCTAssertEqual(++orderValidator, 3) exes[2].fulfill() }.silenceWarning() } } describe("even when one handler is added inside another handler") { testFulfilled(withExpectationCount: 3) { promise, exes, memo in var x = 0 promise.done { _ in XCTAssertEqual(x, 0) x += 1 exes[0].fulfill() promise.done { _ in XCTAssertEqual(x, 2) x += 1 exes[1].fulfill() }.silenceWarning() }.silenceWarning() promise.done { _ in XCTAssertEqual(x, 1) x += 1 exes[2].fulfill() }.silenceWarning() } } } describe("2.2.6.2: If/when `promise` is rejected, all respective `onRejected` callbacks must execute in the order of their originating calls to `then`.") { describe("multiple boring rejection handlers") { testRejected(withExpectationCount: 4) { promise, exes, sentinel in var ticket = 0 promise.catch { err in guard case Error.sentinel(let x) = err, x == sentinel else { return XCTFail() } XCTAssertEqual(++ticket, 1) exes[0].fulfill() } promise.done { _ in XCTFail() }.silenceWarning() promise.catch { err in guard case Error.sentinel(let x) = err, x == sentinel else { return XCTFail() } XCTAssertEqual(++ticket, 2) exes[1].fulfill() } promise.done { _ in XCTFail() }.silenceWarning() promise.catch { err in guard case Error.sentinel(let x) = err, x == sentinel else { return XCTFail() } XCTAssertEqual(++ticket, 3) exes[2].fulfill() } promise.done { _ in XCTFail() }.silenceWarning() promise.catch { err in guard case Error.sentinel(let x) = err, x == sentinel else { return XCTFail() } XCTAssertEqual(++ticket, 4) exes[3].fulfill() } } } describe("multiple rejection handlers, one of which throws") { testRejected(withExpectationCount: 4) { promise, exes, sentinel in var orderValidator = 0 promise.catch { err in guard case Error.sentinel(let x) = err, x == sentinel else { return XCTFail() } XCTAssertEqual(++orderValidator, 1) exes[0].fulfill() } promise.done { _ in XCTFail() }.silenceWarning() promise.catch { err in guard case Error.sentinel(let x) = err, x == sentinel else { return XCTFail() } XCTAssertEqual(++orderValidator, 2) exes[1].fulfill() } promise.done { _ in XCTFail() }.silenceWarning() promise.recover { err -> Promise in if case Error.sentinel(let x) = err { XCTAssertEqual(x, sentinel) } else { XCTFail() } XCTAssertEqual(++orderValidator, 3) exes[2].fulfill() throw Error.dummy }.silenceWarning() promise.done { _ in XCTFail() }.silenceWarning() promise.catch { err in guard case Error.sentinel(let x) = err, x == sentinel else { return XCTFail() } XCTAssertEqual(++orderValidator, 4) exes[3].fulfill() } } } describe("results in multiple branching chains with their own fulfillment values") { testRejected(withExpectationCount: 3) { promise, exes, memo in let sentinel1 = arc4random() let sentinel2 = arc4random() let sentinel3 = arc4random() promise.recover { _ in return .value(sentinel1) }.done { value in XCTAssertEqual(sentinel1, value) exes[0].fulfill() } promise.recover { _ -> Promise in throw Error.sentinel(sentinel2) }.catch { err in if case Error.sentinel(let x) = err, x == sentinel2 { exes[1].fulfill() } } promise.recover { _ in .value(sentinel3) }.done { value in XCTAssertEqual(value, sentinel3) exes[2].fulfill() } } } describe("`onRejected` handlers are called in the original order") { testRejected(withExpectationCount: 3) { promise, exes, memo in var x = 0 promise.catch { _ in XCTAssertEqual(x, 0) x += 1 exes[0].fulfill() } promise.catch { _ in XCTAssertEqual(x, 1) x += 1 exes[1].fulfill() } promise.catch { _ in XCTAssertEqual(x, 2) x += 1 exes[2].fulfill() } } } describe("even when one handler is added inside another handler") { testRejected(withExpectationCount: 3) { promise, exes, memo in var x = 0 promise.catch { _ in XCTAssertEqual(x, 0) x += 1 exes[0].fulfill() promise.catch { _ in XCTAssertEqual(x, 2) x += 1 exes[1].fulfill() } } promise.catch { _ in XCTAssertEqual(x, 1) x += 1 exes[2].fulfill() } } } } } } } ================================================ FILE: Tests/A+/2.2.7.swift ================================================ import PromiseKit import XCTest class Test227: XCTestCase { func test() { describe("2.2.7: `then` must return a promise: `promise2 = promise1.then(onFulfilled, onRejected)") { describe("2.2.7.2: If either `onFulfilled` or `onRejected` throws an exception `e`, `promise2` must be rejected with `e` as the reason.") { testFulfilled { promise1, expectation, _ in let sentinel = arc4random() let promise2 = promise1.done { _ in throw Error.sentinel(sentinel) } promise2.catch { if case Error.sentinel(let x) = $0, x == sentinel { expectation.fulfill() } } } testRejected { promise1, expectation, _ in let sentinel = arc4random() let promise2 = promise1.recover { _ -> Promise in throw Error.sentinel(sentinel) } promise2.catch { error in if case Error.sentinel(let x) = error, x == sentinel { expectation.fulfill() } } } } } } } ================================================ FILE: Tests/A+/2.3.1.swift ================================================ import PromiseKit import XCTest class Test231: XCTestCase { func test() { describe("2.3.1: If `promise` and `x` refer to the same object, reject `promise` with a `TypeError' as the reason.") { specify("via return from a fulfilled promise") { d, expectation in var promise: Promise! promise = Promise().then { () -> Promise in return promise } promise.catch { err in if case PMKError.returnedSelf = err { expectation.fulfill() } } } specify("via return from a rejected promise") { d, expectation in var promise: Promise! promise = Promise(error: Error.dummy).recover { _ -> Promise in return promise } promise.catch { err in if case PMKError.returnedSelf = err { expectation.fulfill() } } } } } } ================================================ FILE: Tests/A+/2.3.2.swift ================================================ import PromiseKit import XCTest class Test232: XCTestCase { func test() { describe("2.3.2: If `x` is a promise, adopt its state") { describe("2.3.2.1: If `x` is pending, `promise` must remain pending until `x` is fulfilled or rejected.") { func xFactory() -> Promise { return Promise.pending().promise } testPromiseResolution(factory: xFactory) { promise, expectation in var wasFulfilled = false; var wasRejected = false; promise.test(onFulfilled: { wasFulfilled = true }, onRejected: { wasRejected = true }) after(ticks: 4) { XCTAssertFalse(wasFulfilled) XCTAssertFalse(wasRejected) expectation.fulfill() } } } describe("2.3.2.2: If/when `x` is fulfilled, fulfill `promise` with the same value.") { describe("`x` is already-fulfilled") { let sentinel = arc4random() func xFactory() -> Promise { return .value(sentinel) } testPromiseResolution(factory: xFactory) { promise, expectation in promise.done { XCTAssertEqual($0, sentinel) expectation.fulfill() }.silenceWarning() } } describe("`x` is eventually-fulfilled") { let sentinel = arc4random() func xFactory() -> Promise { return Promise { seal in after(ticks: 2) { seal.fulfill(sentinel) } } } testPromiseResolution(factory: xFactory) { promise, expectation in promise.done { XCTAssertEqual($0, sentinel) expectation.fulfill() }.silenceWarning() } } } describe("2.3.2.3: If/when `x` is rejected, reject `promise` with the same reason.") { describe("`x` is already-rejected") { let sentinel = arc4random() func xFactory() -> Promise { return Promise(error: Error.sentinel(sentinel)) } testPromiseResolution(factory: xFactory) { promise, expectation in promise.catch { err in if case Error.sentinel(let value) = err, value == sentinel { expectation.fulfill() } } } } describe("`x` is eventually-rejected") { let sentinel = arc4random() func xFactory() -> Promise { return Promise { seal in after(ticks: 2) { seal.reject(Error.sentinel(sentinel)) } } } testPromiseResolution(factory: xFactory) { promise, expectation in promise.catch { err in if case Error.sentinel(let value) = err, value == sentinel { expectation.fulfill() } } } } } } } } ///////////////////////////////////////////////////////////////////////// extension Test232 { fileprivate func testPromiseResolution(factory: @escaping () -> Promise, line: UInt = #line, test: (Promise, XCTestExpectation) -> Void) { specify("via return from a fulfilled promise", file: #file, line: line) { d, expectation in let promise = Promise.value(arc4random()).then { _ in factory() } test(promise, expectation) } specify("via return from a rejected promise", file: #file, line: line) { d, expectation in let promise: Promise = Promise(error: Error.dummy).recover { _ in factory() } test(promise, expectation) } } } ================================================ FILE: Tests/A+/2.3.4.swift ================================================ import PromiseKit import XCTest class Test234: XCTestCase { func test() { describe("2.3.4: If `x` is not an object or function, fulfill `promise` with `x`") { testFulfilled { promise, exception, _ in promise.map { value -> UInt32 in return 1 }.done { value in XCTAssertEqual(value, 1) exception.fulfill() }.silenceWarning() } testRejected { promise, expectation, _ in promise.recover { _ -> Promise in return .value(UInt32(1)) }.done { value in XCTAssertEqual(value, 1) expectation.fulfill() }.silenceWarning() } } } } ================================================ FILE: Tests/A+/README.md ================================================ Resources ========= * https://github.com/promises-aplus/promises-tests Skipped ======= * 2.3.3: Otherwise, if x is an object or function. This spec is a NOOP for Swift: - We have decided not to interact with other Promises A+ implementations - functions cannot have properties * 2.3.3.4: If then is not a function, fulfill promise with x. - See: The 2.3.4 suite. ================================================ FILE: Tests/A+/XCTestManifests.swift ================================================ #if !canImport(ObjectiveC) import XCTest #if os(Android) extension XCTestExpectation { func fulfill() { fulfill(#file, line: #line) } } #endif extension Test212 { // DO NOT MODIFY: This is autogenerated, use: // `swift test --generate-linuxmain` // to regenerate. static let __allTests__Test212 = [ ("test", test), ] } extension Test213 { // DO NOT MODIFY: This is autogenerated, use: // `swift test --generate-linuxmain` // to regenerate. static let __allTests__Test213 = [ ("test", test), ] } extension Test222 { // DO NOT MODIFY: This is autogenerated, use: // `swift test --generate-linuxmain` // to regenerate. static let __allTests__Test222 = [ ("test", test), ] } extension Test223 { // DO NOT MODIFY: This is autogenerated, use: // `swift test --generate-linuxmain` // to regenerate. static let __allTests__Test223 = [ ("test", test), ] } extension Test224 { // DO NOT MODIFY: This is autogenerated, use: // `swift test --generate-linuxmain` // to regenerate. static let __allTests__Test224 = [ ("test", test), ] } extension Test226 { // DO NOT MODIFY: This is autogenerated, use: // `swift test --generate-linuxmain` // to regenerate. static let __allTests__Test226 = [ ("test", test), ] } extension Test227 { // DO NOT MODIFY: This is autogenerated, use: // `swift test --generate-linuxmain` // to regenerate. static let __allTests__Test227 = [ ("test", test), ] } extension Test231 { // DO NOT MODIFY: This is autogenerated, use: // `swift test --generate-linuxmain` // to regenerate. static let __allTests__Test231 = [ ("test", test), ] } extension Test232 { // DO NOT MODIFY: This is autogenerated, use: // `swift test --generate-linuxmain` // to regenerate. static let __allTests__Test232 = [ ("test", test), ] } extension Test234 { // DO NOT MODIFY: This is autogenerated, use: // `swift test --generate-linuxmain` // to regenerate. static let __allTests__Test234 = [ ("test", test), ] } public func __allTests() -> [XCTestCaseEntry] { return [ testCase(Test212.__allTests__Test212), testCase(Test213.__allTests__Test213), testCase(Test222.__allTests__Test222), testCase(Test223.__allTests__Test223), testCase(Test224.__allTests__Test224), testCase(Test226.__allTests__Test226), testCase(Test227.__allTests__Test227), testCase(Test231.__allTests__Test231), testCase(Test232.__allTests__Test232), testCase(Test234.__allTests__Test234), ] } #endif ================================================ FILE: Tests/Bridging/BridgingTests.m ================================================ @import PromiseKit; @import XCTest; #import "Infrastructure.h" @interface BridgingTests: XCTestCase @end @implementation BridgingTests - (void)testChainAnyPromiseFromSwiftCode { XCTestExpectation *ex = [self expectationWithDescription:@""]; AnyPromise *promise = PMKAfter(0.02); for (int x = 0; x < 100; ++x) { promise = promise.then(^{ return [[[PromiseBridgeHelper alloc] init] bridge1]; }); } promise.then(^{ [ex fulfill]; }); [self waitForExpectationsWithTimeout:20 handler:nil]; } - (void)test626 { XCTestExpectation *ex = [self expectationWithDescription:@""]; testCase626().then(^{ XCTFail(); }).ensure(^{ [ex fulfill]; }); [self waitForExpectationsWithTimeout:20 handler:nil]; } @end ================================================ FILE: Tests/Bridging/BridgingTests.swift ================================================ import Foundation import PromiseKit import XCTest class BridgingTests: XCTestCase { func testCanBridgeAnyObject() { let sentinel = NSURLRequest() let p = Promise.value(sentinel) let ap = AnyPromise(p) XCTAssertEqual(ap.value(forKey: "value") as? NSURLRequest, sentinel) } func testCanBridgeOptional() { let sentinel: NSURLRequest? = NSURLRequest() let p = Promise.value(sentinel) let ap = AnyPromise(p) XCTAssertEqual(ap.value(forKey: "value") as? NSURLRequest, sentinel) } func testCanBridgeSwiftArray() { let sentinel = [NSString(), NSString(), NSString()] let p = Promise.value(sentinel) let ap = AnyPromise(p) guard let foo = ap.value(forKey: "value") as? [NSString] else { return XCTFail() } XCTAssertEqual(foo, sentinel) } func testCanBridgeSwiftDictionary() { let sentinel = [NSString(): NSString()] let p = Promise.value(sentinel) let ap = AnyPromise(p) guard let foo = ap.value(forKey: "value") as? [NSString: NSString] else { return XCTFail() } XCTAssertEqual(foo, sentinel) } func testCanBridgeInt() { let sentinel = 3 let p = Promise.value(sentinel) let ap = AnyPromise(p) XCTAssertEqual(ap.value(forKey: "value") as? Int, sentinel) } func testCanBridgeString() { let sentinel = "a" let p = Promise.value(sentinel) let ap = AnyPromise(p) XCTAssertEqual(ap.value(forKey: "value") as? String, sentinel) } func testCanBridgeBool() { let sentinel = true let p = Promise.value(sentinel) let ap = AnyPromise(p) XCTAssertEqual(ap.value(forKey: "value") as? Bool, sentinel) } func testCanChainOffAnyPromiseFromObjC() { let ex = expectation(description: "") firstly { .value(1) }.then { _ -> AnyPromise in return PromiseBridgeHelper().value(forKey: "bridge2") as! AnyPromise }.done { value in XCTAssertEqual(123, value as? Int) ex.fulfill() }.silenceWarning() waitForExpectations(timeout: 1) } func testCanThenOffAnyPromise() { let ex = expectation(description: "") PMKDummyAnyPromise_YES().then { obj -> Promise in if let value = obj as? NSNumber { XCTAssertEqual(value, NSNumber(value: true)) ex.fulfill() } return Promise() }.silenceWarning() waitForExpectations(timeout: 1) } func testCanThenOffManifoldAnyPromise() { let ex = expectation(description: "") PMKDummyAnyPromise_Manifold().then { obj -> Promise in defer { ex.fulfill() } XCTAssertEqual(obj as? NSNumber, NSNumber(value: true), "\(obj ?? "nil") is not @YES") return Promise() }.silenceWarning() waitForExpectations(timeout: 1) } func testCanAlwaysOffAnyPromise() { let ex = expectation(description: "") PMKDummyAnyPromise_YES().then { obj -> Promise in ex.fulfill() return Promise() }.silenceWarning() waitForExpectations(timeout: 1) } func testCanCatchOffAnyPromise() { let ex = expectation(description: "") PMKDummyAnyPromise_Error().catch { err in ex.fulfill() } waitForExpectations(timeout: 1) } func testAsPromise() { #if swift(>=3.1) XCTAssertTrue(Promise(PMKDummyAnyPromise_Error()).isRejected) XCTAssertEqual(Promise(PMKDummyAnyPromise_YES()).value as? NSNumber, NSNumber(value: true)) #else XCTAssertTrue(PMKDummyAnyPromise_Error().asPromise().isRejected) XCTAssertEqual(PMKDummyAnyPromise_YES().asPromise().value as? NSNumber, NSNumber(value: true)) #endif } func testFirstlyReturningAnyPromiseSuccess() { let ex = expectation(description: "") firstly { PMKDummyAnyPromise_Error() }.catch { error in ex.fulfill() } waitForExpectations(timeout: 1) } func testFirstlyReturningAnyPromiseError() { let ex = expectation(description: "") firstly { PMKDummyAnyPromise_YES() }.done { _ in ex.fulfill() }.silenceWarning() waitForExpectations(timeout: 1) } func test1() { let ex = expectation(description: "") // AnyPromise.then { return x } let input = after(seconds: 0).map{ 1 } AnyPromise(input).then { obj -> Promise in XCTAssertEqual(obj as? Int, 1) return .value(2) }.done { value in XCTAssertEqual(value, 2) ex.fulfill() }.silenceWarning() waitForExpectations(timeout: 1) } func test2() { let ex = expectation(description: "") // AnyPromise.then { return AnyPromise } let input = after(seconds: 0).map{ 1 } AnyPromise(input).then { obj -> AnyPromise in XCTAssertEqual(obj as? Int, 1) return AnyPromise(after(seconds: 0).map{ 2 }) }.done { obj in XCTAssertEqual(obj as? Int, 2) ex.fulfill() }.silenceWarning() waitForExpectations(timeout: 1) } func test3() { let ex = expectation(description: "") // AnyPromise.then { return Promise } let input = after(seconds: 0).map{ 1 } AnyPromise(input).then { obj -> Promise in XCTAssertEqual(obj as? Int, 1) return after(seconds: 0).map{ 2 } }.done { value in XCTAssertEqual(value, 2) ex.fulfill() }.silenceWarning() waitForExpectations(timeout: 1, handler: nil) } // can return AnyPromise (that fulfills) in then handler func test4() { let ex = expectation(description: "") Promise.value(1).then { _ -> AnyPromise in return AnyPromise(after(seconds: 0).map{ 1 }) }.done { x in XCTAssertEqual(x as? Int, 1) ex.fulfill() }.silenceWarning() waitForExpectations(timeout: 1, handler: nil) } // can return AnyPromise (that rejects) in then handler func test5() { let ex = expectation(description: "") Promise.value(1).then { _ -> AnyPromise in let promise = after(.milliseconds(100)).done{ throw Error.dummy } return AnyPromise(promise) }.catch { err in ex.fulfill() } waitForExpectations(timeout: 1) } func testStandardSwiftBridgeIsUnambiguous() { let p = Promise.value(1) let q = Promise(p) XCTAssertEqual(p.value, q.value) } /// testing NSError to Error for cancelledError types func testErrorCancellationBridging() { let ex = expectation(description: "") let p = Promise().done { throw LocalError.cancel as NSError } p.catch { _ in XCTFail() } p.catch(policy: .allErrors) { XCTAssertTrue($0.isCancelled) ex.fulfill() } waitForExpectations(timeout: 1) // here we verify that Swift’s NSError bridging works as advertised XCTAssertTrue(LocalError.cancel.isCancelled) XCTAssertTrue((LocalError.cancel as NSError).isCancelled) } } private enum Error: Swift.Error { case dummy } extension Promise { func silenceWarning() {} } private enum LocalError: CancellableError { case notCancel case cancel var isCancelled: Bool { switch self { case .notCancel: return false case .cancel: return true } } } ================================================ FILE: Tests/Bridging/Infrastructure.h ================================================ @import Foundation; @class AnyPromise; AnyPromise *PMKDummyAnyPromise_YES(void); AnyPromise *PMKDummyAnyPromise_Manifold(void); AnyPromise *PMKDummyAnyPromise_Error(void); __attribute__((objc_runtime_name("PMKPromiseBridgeHelper"))) __attribute__((objc_subclassing_restricted)) @interface PromiseBridgeHelper: NSObject - (AnyPromise *)bridge1; @end AnyPromise *testCase626(void); ================================================ FILE: Tests/Bridging/Infrastructure.m ================================================ @import Foundation; @import PromiseKit; #import "Infrastructure.h" AnyPromise *PMKDummyAnyPromise_YES(void) { return [AnyPromise promiseWithValue:@YES]; } AnyPromise *PMKDummyAnyPromise_Manifold(void) { return [AnyPromise promiseWithValue:PMKManifold(@YES, @NO, @NO)]; } AnyPromise *PMKDummyAnyPromise_Error(void) { return [AnyPromise promiseWithValue:[NSError errorWithDomain:@"a" code:1 userInfo:nil]]; } @implementation PromiseBridgeHelper (objc) - (AnyPromise *)bridge2 { return [AnyPromise promiseWithResolverBlock:^(PMKResolver resolve) { dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ resolve(@123); }); }]; } @end #import "PMKBridgeTests-Swift.h" AnyPromise *testCase626(void) { return PMKWhen(@[[TestPromise626 promise], [TestPromise626 promise]]).then(^(id value){ NSLog(@"Success: %@", value); }).catch(^(NSError *error) { NSLog(@"Error: %@", error); @throw error; }); } ================================================ FILE: Tests/Bridging/Infrastructure.swift ================================================ import PromiseKit // for BridgingTests.m @objc(PMKPromiseBridgeHelper) class PromiseBridgeHelper: NSObject { @objc func bridge1() -> AnyPromise { let p = after(.milliseconds(10)) return AnyPromise(p) } } enum MyError: Error { case PromiseError } @objc class TestPromise626: NSObject { @objc class func promise() -> AnyPromise { let promise: Promise = Promise { seal in seal.reject(MyError.PromiseError) } return AnyPromise(promise) } } ================================================ FILE: Tests/CoreObjC/AnyPromiseTests.m ================================================ @import PromiseKit; @import XCTest; #import "Infrastructure.h" #define PMKTestErrorDomain @"PMKTestErrorDomain" static inline NSError *dummyWithCode(NSInteger code) { return [NSError errorWithDomain:PMKTestErrorDomain code:rand() userInfo:@{NSLocalizedDescriptionKey: @(code).stringValue}]; } static inline NSError *dummy(void) { return dummyWithCode(rand()); } static inline AnyPromise *rejectLater(void) { return [AnyPromise promiseWithResolverBlock:^(PMKResolver resolve) { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ dispatch_async(dispatch_get_main_queue(), ^{ resolve(dummy()); }); }); }]; } static inline AnyPromise *fulfillLater(void) { return [AnyPromise promiseWithResolverBlock:^(PMKResolver resolve) { dispatch_async(dispatch_get_global_queue(QOS_CLASS_UNSPECIFIED, 0), ^{ resolve(@1); }); }]; } @interface AnyPromiseTestSuite : XCTestCase @end @implementation AnyPromiseTestSuite - (void)test_01_resolve { id ex1 = [self expectationWithDescription:@""]; AnyPromise *promise = [AnyPromise promiseWithResolverBlock:^(PMKResolver resolve) { resolve(@1); }]; promise.then(^(NSNumber *o){ [ex1 fulfill]; XCTAssertEqual(o.intValue, 1); }); promise.catch(^{ XCTFail(); }); [self waitForExpectationsWithTimeout:1 handler:nil]; } - (void)test_02_reject { id ex1 = [self expectationWithDescription:@""]; AnyPromise *promise = [AnyPromise promiseWithResolverBlock:^(PMKResolver resolve) { resolve(dummyWithCode(2)); }]; promise.then(^{ XCTFail(); }); promise.catch(^(NSError *error){ XCTAssertEqualObjects(error.localizedDescription, @"2"); [ex1 fulfill]; }); [self waitForExpectationsWithTimeout:1 handler:nil]; } - (void)test_03_return_error { id ex1 = [self expectationWithDescription:@""]; AnyPromise *promise = [AnyPromise promiseWithResolverBlock:^(PMKResolver resolve) { resolve(@2); }]; promise.then(^{ return [NSError errorWithDomain:@"a" code:3 userInfo:nil]; }).catch(^(NSError *e){ [ex1 fulfill]; XCTAssertEqual(3, e.code); }); promise.catch(^{ XCTFail(); }); [self waitForExpectationsWithTimeout:1 handler:nil]; } - (void)test_04_return_error_doesnt_compromise_result { id ex1 = [self expectationWithDescription:@""]; AnyPromise *promise = [AnyPromise promiseWithResolverBlock:^(PMKResolver resolve) { resolve(@4); }].then(^{ return dummy(); }); promise.then(^{ XCTFail(); }); promise.catch(^{ [ex1 fulfill]; }); [self waitForExpectationsWithTimeout:1 handler:nil]; } - (void)test_05_throw_and_bubble { id ex1 = [self expectationWithDescription:@""]; [AnyPromise promiseWithResolverBlock:^(PMKResolver resolve) { resolve(@5); }].then(^(id ii){ XCTAssertEqual(5, [ii intValue]); return [NSError errorWithDomain:@"a" code:[ii intValue] userInfo:nil]; }).catch(^(NSError *e){ XCTAssertEqual(e.code, 5); [ex1 fulfill]; }); [self waitForExpectationsWithTimeout:1 handler:nil]; } - (void)test_05_throw_and_bubble_more { id ex1 = [self expectationWithDescription:@""]; [AnyPromise promiseWithResolverBlock:^(PMKResolver resolve) { resolve(@5); }].then(^{ return dummy(); }).then(^{ //NOOP }).catch(^(NSError *e){ [ex1 fulfill]; XCTAssertEqualObjects(e.domain, PMKTestErrorDomain); }); [self waitForExpectationsWithTimeout:1 handler:nil]; } - (void)test_06_return_error { id ex1 = [self expectationWithDescription:@""]; [AnyPromise promiseWithResolverBlock:^(PMKResolver resolve) { resolve(@5); }].then(^{ return dummy(); }).catch(^{ [ex1 fulfill]; }); [self waitForExpectationsWithTimeout:1 handler:nil]; } - (void)test_07_can_then_resolved { id ex1 = [self expectationWithDescription:@""]; [AnyPromise promiseWithResolverBlock:^(PMKResolver resolve) { resolve(@1); }].then(^(id o){ [ex1 fulfill]; XCTAssertEqualObjects(@1, o); }); [self waitForExpectationsWithTimeout:1 handler:nil]; } - (void)test_07a_can_fail_rejected { id ex1 = [self expectationWithDescription:@""]; [AnyPromise promiseWithResolverBlock:^(PMKResolver resolve) { resolve(dummyWithCode(1)); }].catch(^(NSError *e){ [ex1 fulfill]; XCTAssertEqualObjects(@"1", e.localizedDescription); }); [self waitForExpectationsWithTimeout:1 handler:nil]; } - (void)test_09_async { id ex1 = [self expectationWithDescription:@""]; __block int x = 0; [AnyPromise promiseWithResolverBlock:^(PMKResolver resolve) { resolve(@1); }].then(^{ XCTAssertEqual(x, 0); x++; }).then(^{ XCTAssertEqual(x, 1); x++; }).then(^{ XCTAssertEqual(x, 2); x++; }).then(^{ XCTAssertEqual(x, 3); x++; }).then(^{ XCTAssertEqual(x, 4); x++; [ex1 fulfill]; }); [self waitForExpectationsWithTimeout:1 handler:nil]; XCTAssertEqual(x, 5); } - (void)test_10_then_returns_resolved_promise { id ex1 = [self expectationWithDescription:@""]; [AnyPromise promiseWithResolverBlock:^(PMKResolver resolve) { resolve(@10); }].then(^(id o){ XCTAssertEqualObjects(@10, o); return [AnyPromise promiseWithResolverBlock:^(PMKResolver resolve) { resolve(@100); }]; }).then(^(id o){ XCTAssertEqualObjects(@100, o); [ex1 fulfill]; }); [self waitForExpectationsWithTimeout:1 handler:nil]; } - (void)test_11_then_returns_pending_promise { id ex1 = [self expectationWithDescription:@""]; [AnyPromise promiseWithResolverBlock:^(PMKResolver resolve) { resolve(@1); }].then(^{ return fulfillLater(); }).then(^(id o){ [ex1 fulfill]; }); [self waitForExpectationsWithTimeout:1 handler:nil]; } - (void)test_12_then_returns_recursive_promises { id ex1 = [self expectationWithDescription:@""]; id ex2 = [self expectationWithDescription:@""]; __block int x = 0; fulfillLater().then(^{ NSLog(@"1"); XCTAssertEqual(x++, 0); return fulfillLater().then(^{ NSLog(@"2"); XCTAssertEqual(x++, 1); return fulfillLater().then(^{ NSLog(@"3"); XCTAssertEqual(x++, 2); return fulfillLater().then(^{ NSLog(@"4"); XCTAssertEqual(x++, 3); [ex2 fulfill]; return @"foo"; }); }); }); }).then(^(id o){ NSLog(@"5"); XCTAssertEqualObjects(@"foo", o); XCTAssertEqual(x++, 4); [ex1 fulfill]; }); [self waitForExpectationsWithTimeout:1 handler:nil]; XCTAssertEqual(x, 5); } - (void)test_13_then_returns_recursive_promises_that_fails { id ex1 = [self expectationWithDescription:@""]; id ex2 = [self expectationWithDescription:@""]; fulfillLater().then(^{ return fulfillLater().then(^{ return fulfillLater().then(^{ return fulfillLater().then(^{ [ex2 fulfill]; return dummy(); }); }); }); }).then(^{ XCTFail(); }).catch(^(NSError *e){ XCTAssertEqualObjects(e.domain, PMKTestErrorDomain); [ex1 fulfill]; }); [self waitForExpectationsWithTimeout:1 handler:nil]; } - (void)test_14_fail_returns_value { id ex1 = [self expectationWithDescription:@""]; [AnyPromise promiseWithResolverBlock:^(PMKResolver resolve) { resolve(@1); }].then(^{ return [NSError errorWithDomain:@"a" code:1 userInfo:nil]; }).catch(^(NSError *e){ XCTAssertEqual(e.code, 1); return @2; }).then(^(id o){ XCTAssertEqualObjects(o, @2); [ex1 fulfill]; }); [self waitForExpectationsWithTimeout:1 handler:nil]; } - (void)test_15_fail_returns_promise { id ex1 = [self expectationWithDescription:@""]; [AnyPromise promiseWithResolverBlock:^(PMKResolver resolve) { resolve(@1); }].then(^{ return dummy(); }).catch(^{ return fulfillLater().then(^{ return @123; }); }).then(^(id o){ XCTAssertEqualObjects(o, @123); [ex1 fulfill]; }); [self waitForExpectationsWithTimeout:1 handler:nil]; } - (void)test_23_add_another_fail_to_already_rejected { id ex1 = [self expectationWithDescription:@""]; id ex2 = [self expectationWithDescription:@""]; PMKResolver resolve; AnyPromise *promise = [[AnyPromise alloc] initWithResolver:&resolve]; promise.then(^{ XCTFail(); }).catch(^(NSError *e){ XCTAssertEqualObjects(e.localizedDescription, @"23"); [ex1 fulfill]; }); resolve(dummyWithCode(23)); promise.then(^{ XCTFail(); }).catch(^(NSError *e){ XCTAssertEqualObjects(e.localizedDescription, @"23"); [ex2 fulfill]; }); [self waitForExpectationsWithTimeout:1 handler:nil]; } - (void)test_25_then_plus_deferred_plus_GCD { id ex1 = [self expectationWithDescription:@""]; id ex2 = [self expectationWithDescription:@""]; id ex3 = [self expectationWithDescription:@""]; fulfillLater().then(^(id o){ [ex1 fulfill]; return fulfillLater().then(^{ return @YES; }); }).then(^(id o){ XCTAssertEqualObjects(@YES, o); [ex2 fulfill]; }).then(^(id o){ XCTAssertNil(o); [ex3 fulfill]; }).catch(^{ XCTFail(); }); [self waitForExpectationsWithTimeout:1 handler:nil]; } - (void)test_26_promise_then_promise_fail_promise_fail { id ex1 = [self expectationWithDescription:@""]; fulfillLater().then(^{ return fulfillLater().then(^{ return dummy(); }).catch(^{ return fulfillLater().then(^{ return dummy(); }); }); }).then(^{ XCTFail(); }).catch(^{ [ex1 fulfill]; }); [self waitForExpectationsWithTimeout:1 handler:nil];} - (void)test_27_eat_failure { id ex1 = [self expectationWithDescription:@""]; fulfillLater().then(^{ return dummy(); }).catch(^{ return @YES; }).then(^{ [ex1 fulfill]; }); [self waitForExpectationsWithTimeout:1 handler:nil]; } - (void)test_28_deferred_rejected_catch_promise { id ex1 = [self expectationWithDescription:@""]; id ex2 = [self expectationWithDescription:@""]; rejectLater().catch(^{ [ex1 fulfill]; return fulfillLater(); }).then(^(id o){ [ex2 fulfill]; }).catch(^{ XCTFail(); }); [self waitForExpectationsWithTimeout:1 handler:nil]; } - (void)test_29_deferred_rejected_catch_promise { id ex1 = [self expectationWithDescription:@""]; id ex2 = [self expectationWithDescription:@""]; rejectLater().catch(^{ [ex1 fulfill]; return fulfillLater().then(^{ return dummy(); }); }).then(^{ XCTFail(@"1"); }).catch(^(NSError *error){ [ex2 fulfill]; }).catch(^{ XCTFail(@"2"); }); [self waitForExpectationsWithTimeout:1 handler:nil]; } - (void)test_30_dispatch_returns_pending_promise { id ex1 = [self expectationWithDescription:@""]; dispatch_promise(^{ return fulfillLater(); }).then(^{ [ex1 fulfill]; }); [self waitForExpectationsWithTimeout:1 handler:nil]; } - (void)test_31_dispatch_returns_promise { id ex1 = [self expectationWithDescription:@""]; dispatch_promise(^{ return [AnyPromise promiseWithValue:@1]; }).then(^(id o){ XCTAssertEqualObjects(o, @1); [ex1 fulfill]; }); [self waitForExpectationsWithTimeout:1 handler:nil]; } - (void)test_32_return_primitive { id ex1 = [self expectationWithDescription:@""]; __block void (^fulfiller)(id) = nil; [AnyPromise promiseWithResolverBlock:^(PMKResolver resolve) { fulfiller = resolve; }].then(^(id o){ XCTAssertEqualObjects(o, @32); return 3; }).then(^(id o){ XCTAssertEqualObjects(@3, o); [ex1 fulfill]; }); fulfiller(@32); [self waitForExpectationsWithTimeout:1 handler:nil]; } - (void)test_33_return_nil { id ex1 = [self expectationWithDescription:@""]; [AnyPromise promiseWithValue:@1].then(^(id o){ XCTAssertEqualObjects(o, @1); return nil; }).then(^{ return nil; }).then(^(id o){ XCTAssertNil(o); [ex1 fulfill]; }); [self waitForExpectationsWithTimeout:1 handler:nil]; } - (void)test_33a_return_nil { id ex1 = [self expectationWithDescription:@""]; id ex2 = [self expectationWithDescription:@""]; [AnyPromise promiseWithValue:@"HI"].then(^(id o){ XCTAssertEqualObjects(o, @"HI"); [ex1 fulfill]; return nil; }).then(^{ return nil; }).then(^{ [ex2 fulfill]; return nil; }); [self waitForExpectationsWithTimeout:1 handler:nil]; } - (void)test_36_promise_with_value_nil { id ex1 = [self expectationWithDescription:@""]; [AnyPromise promiseWithValue:nil].then(^(id o){ XCTAssertNil(o); [ex1 fulfill]; }); [self waitForExpectationsWithTimeout:1 handler:nil]; } - (void)test_42 { id ex1 = [self expectationWithDescription:@""]; [AnyPromise promiseWithValue:@1].then(^{ return fulfillLater(); }).then(^{ [ex1 fulfill]; }); [self waitForExpectationsWithTimeout:1 handler:nil]; } - (void)test_43_return_promise_from_itself { id ex1 = [self expectationWithDescription:@""]; AnyPromise *p = fulfillLater().then(^{ return @1; }); p.then(^{ return p; }).then(^{ [ex1 fulfill]; }); [self waitForExpectationsWithTimeout:1 handler:nil]; } - (void)test_44_reseal { id ex1 = [self expectationWithDescription:@""]; [AnyPromise promiseWithResolverBlock:^(PMKResolver resolve) { resolve(@123); resolve(@234); }].then(^(id o){ XCTAssertEqualObjects(o, @123); [ex1 fulfill]; }); [self waitForExpectationsWithTimeout:1 handler:nil]; } - (void)test_46_test_then_on { id ex1 = [self expectationWithDescription:@""]; dispatch_queue_t q1 = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0); dispatch_queue_t q2 = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0); #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" [AnyPromise promiseWithValue:@1].thenOn(q1, ^{ XCTAssertFalse([NSThread isMainThread]); return dispatch_get_current_queue(); }).thenOn(q2, ^(id q){ XCTAssertFalse([NSThread isMainThread]); XCTAssertNotEqualObjects(q, dispatch_get_current_queue()); [ex1 fulfill]; }); #pragma clang diagnostic pop [self waitForExpectationsWithTimeout:1 handler:nil]; } - (void)test_47_finally_plus { id ex1 = [self expectationWithDescription:@""]; [AnyPromise promiseWithValue:@1].then(^{ return @1; }).ensure(^{ [ex1 fulfill]; }); [self waitForExpectationsWithTimeout:1 handler:nil]; } - (void)test_48_finally_negative { @autoreleasepool { id ex1 = [self expectationWithDescription:@"always"]; id ex2 = [self expectationWithDescription:@"errorUnhandler"]; [AnyPromise promiseWithValue:@1].then(^{ return dummy(); }).ensure(^{ [ex1 fulfill]; }).catch(^(NSError *err){ XCTAssertEqualObjects(err.domain, PMKTestErrorDomain); [ex2 fulfill]; }); } [self waitForExpectationsWithTimeout:1 handler:nil]; } - (void)test_49_finally_negative_later { id ex1 = [self expectationWithDescription:@""]; __block int x = 0; [AnyPromise promiseWithValue:@1].then(^{ XCTAssertEqual(++x, 1); return dummy(); }).catch(^{ XCTAssertEqual(++x, 2); }).then(^{ XCTAssertEqual(++x, 3); }).ensure(^{ XCTAssertEqual(++x, 4); [ex1 fulfill]; }); [self waitForExpectationsWithTimeout:1 handler:nil]; } - (void)test_50_fulfill_with_pending_promise { id ex1 = [self expectationWithDescription:@""]; [AnyPromise promiseWithResolverBlock:^(PMKResolver resolve) { resolve(fulfillLater().then(^{ return @"HI"; })); }].then(^(id hi){ XCTAssertEqualObjects(hi, @"HI"); [ex1 fulfill]; }); [self waitForExpectationsWithTimeout:1 handler:nil]; } - (void)test_51_fulfill_with_fulfilled_promise { id ex1 = [self expectationWithDescription:@""]; [AnyPromise promiseWithResolverBlock:^(PMKResolver resolve) { resolve([AnyPromise promiseWithValue:@1]); }].then(^(id o){ XCTAssertEqualObjects(o, @1); [ex1 fulfill]; }); [self waitForExpectationsWithTimeout:1 handler:nil]; } - (void)test_52_fulfill_with_rejected_promise { //NEEDEDanypr id ex1 = [self expectationWithDescription:@""]; fulfillLater().then(^{ return [AnyPromise promiseWithResolverBlock:^(PMKResolver resolve) { resolve([AnyPromise promiseWithValue:dummy()]); }]; }).catch(^(NSError *err){ [ex1 fulfill]; }); [self waitForExpectationsWithTimeout:1 handler:nil]; } - (void)test_53_return_rejected_promise { id ex1 = [self expectationWithDescription:@""]; fulfillLater().then(^{ return @1; }).then(^{ return [AnyPromise promiseWithValue:dummy()]; }).catch(^{ [ex1 fulfill]; }); [self waitForExpectationsWithTimeout:1 handler:nil]; } - (void)test_54_reject_with_rejected_promise { id ex1 = [self expectationWithDescription:@""]; [AnyPromise promiseWithResolverBlock:^(PMKResolver resolve) { id err = [NSError errorWithDomain:@"a" code:123 userInfo:nil]; resolve([AnyPromise promiseWithValue:err]); }].catch(^(NSError *err){ XCTAssertEqual(err.code, 123); [ex1 fulfill]; }); [self waitForExpectationsWithTimeout:1 handler:nil]; } - (void)test_58_just_finally { id ex1 = [self expectationWithDescription:@""]; AnyPromise *promise = fulfillLater().then(^{ return nil; }).ensure(^{ [ex1 fulfill]; }); [self waitForExpectationsWithTimeout:1 handler:nil]; id ex2 = [self expectationWithDescription:@""]; promise.ensure(^{ [ex2 fulfill]; }); [self waitForExpectationsWithTimeout:1 handler:nil]; } - (void)test_59_catch_in_background { id ex1 = [self expectationWithDescription:@""]; [AnyPromise promiseWithResolverBlock:^(PMKResolver resolve) { id err = [NSError errorWithDomain:@"a" code:123 userInfo:nil]; resolve(err); }].catchInBackground(^(NSError *err){ XCTAssertEqual(err.code, 123); XCTAssertFalse([NSThread isMainThread]); [ex1 fulfill]; }); [self waitForExpectationsWithTimeout:1 handler:nil]; } - (void)test_60_catch_on_specific_queue { id ex1 = [self expectationWithDescription:@""]; NSString *expectedQueueName = @"specific queue 123"; dispatch_queue_t q = dispatch_queue_create(expectedQueueName.UTF8String, DISPATCH_QUEUE_SERIAL); [AnyPromise promiseWithResolverBlock:^(PMKResolver resolve) { id err = [NSError errorWithDomain:@"a" code:123 userInfo:nil]; resolve(err); }].catchOn(q, ^(NSError *err){ XCTAssertEqual(err.code, 123); XCTAssertFalse([NSThread isMainThread]); NSString *currentQueueName = [NSString stringWithFormat:@"%s", dispatch_queue_get_label(DISPATCH_CURRENT_QUEUE_LABEL)]; XCTAssertEqualObjects(expectedQueueName, currentQueueName); [ex1 fulfill]; }); [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"); XCTAssertNil([AnyPromise promiseWithResolverBlock:^(id a){}].value); XCTAssertTrue([AnyPromise promiseWithResolverBlock:^(id a){}].pending); XCTAssertFalse([AnyPromise promiseWithValue:@1].pending); XCTAssertTrue([AnyPromise promiseWithValue:@1].fulfilled); XCTAssertFalse([AnyPromise promiseWithValue:@1].rejected); } - (void)test_promiseWithValue { XCTAssertEqual([AnyPromise promiseWithValue:@1].value, @1); XCTAssertEqualObjects([[AnyPromise promiseWithValue:dummyWithCode(2)].value localizedDescription], @"2"); XCTAssertEqual([AnyPromise promiseWithValue:[AnyPromise promiseWithValue:@1]].value, @1); } - (void)testInBackground { id ex = [self expectationWithDescription:@""]; PMKAfter(0.1).thenInBackground(^{ [ex fulfill]; }); [self waitForExpectationsWithTimeout:1 handler:nil]; } - (void)testEnsureOn { id ex = [self expectationWithDescription:@""]; PMKAfter(0.1).ensureOn(dispatch_get_global_queue(QOS_CLASS_UNSPECIFIED, 0), ^{ [ex fulfill]; }); [self waitForExpectationsWithTimeout:1 handler:nil]; } - (void)testEnsureInBackground { id ex = [self expectationWithDescription:@""]; PMKAfter(0.1).ensureInBackground(^{ [ex fulfill]; }); [self waitForExpectationsWithTimeout:1 handler:nil]; } - (void)testAdapterBlock { void (^fetch)(PMKAdapter) = ^(PMKAdapter block){ block(@1, nil); }; id ex = [self expectationWithDescription:@""]; [AnyPromise promiseWithAdapterBlock:fetch].then(^(id obj){ XCTAssertEqualObjects(obj, @1); [ex fulfill]; }); [self waitForExpectationsWithTimeout:1 handler:nil]; } - (void)testIntegerAdapterBlock { void (^fetch)(PMKIntegerAdapter) = ^(PMKIntegerAdapter block){ block(1, nil); }; id ex = [self expectationWithDescription:@""]; [AnyPromise promiseWithIntegerAdapterBlock:fetch].then(^(id obj){ XCTAssertEqualObjects(obj, @1); [ex fulfill]; }); [self waitForExpectationsWithTimeout:1 handler:nil]; } - (void)testBooleanAdapterBlock { void (^fetch)(PMKBooleanAdapter) = ^(PMKBooleanAdapter block){ block(YES, nil); }; id ex = [self expectationWithDescription:@""]; [AnyPromise promiseWithBooleanAdapterBlock:fetch].then(^(id obj){ XCTAssertEqualObjects(obj, @YES); [ex fulfill]; }); [self waitForExpectationsWithTimeout:1 handler:nil]; } static NSHashTable *errorArray; - (void)setUp { [super setUp]; errorArray = [NSHashTable weakObjectsHashTable]; } - (void)testErrorLeaks { id ex1 = [self expectationWithDescription:@""]; NSError *error = dummyWithCode(1001); [errorArray addObject:error]; [AnyPromise promiseWithValue:error] .then(^{ XCTFail(); }).catch(^(NSError *e){ XCTAssertEqual(e.localizedDescription.intValue, 1001); }).then(^{ NSError *err = dummyWithCode(1002); [errorArray addObject:err]; return err; }).catch(^(NSError *e){ XCTAssertEqual(e.localizedDescription.intValue, 1002); }).then(^{ NSError *err = dummyWithCode(1003); [errorArray addObject:err]; return [AnyPromise promiseWithResolverBlock:^(PMKResolver resolve){ resolve(err); }]; }).catch(^(NSError *e){ XCTAssertEqual(e.localizedDescription.intValue, 1003); NSError *err = dummyWithCode(1004); [errorArray addObject:err]; return err; }).catch(^(NSError *e){ XCTAssertEqual(e.localizedDescription.intValue, 1004); }).then(^{ NSError *err = dummyWithCode(1005); [errorArray addObject:err]; // throw will lead to leak, if not use complie flag with "-fobjc-arc-exceptions" @throw err; }).catch(^(NSError *e){ XCTAssertEqual(e.localizedDescription.intValue, 1005); }).ensure(^{ [ex1 fulfill]; }); [self waitForExpectationsWithTimeout:1 handler:nil]; } - (void)tearDown { XCTAssertEqual(errorArray.allObjects.count, 0); [super tearDown]; } //- (void)test_nil_block { // [AnyPromise promiseWithValue:@1].then(nil); // [AnyPromise promiseWithValue:@1].thenOn(nil, nil); // [AnyPromise promiseWithValue:@1].catch(nil); // [AnyPromise promiseWithValue:@1].always(nil); // [AnyPromise promiseWithValue:@1].alwaysOn(nil, nil); //} @end ================================================ FILE: Tests/CoreObjC/AnyPromiseTests.swift ================================================ import PromiseKit import XCTest class AnyPromiseTests: XCTestCase { func testFulfilledResult() { switch AnyPromise(Promise.value(true)).result { case .fulfilled(let obj as Bool)? where obj: break default: XCTFail() } } func testRejectedResult() { switch AnyPromise(Promise(error: PMKError.badInput)).result { case .rejected(let err)?: print(err) break default: XCTFail() } } func testPendingResult() { switch AnyPromise(Promise.pending().promise).result { case nil: break default: XCTFail() } } func testCustomStringConvertible() { XCTAssertEqual("\(AnyPromise(Promise.pending().promise))", "AnyPromise(…)") XCTAssertEqual("\(AnyPromise(Promise.value(1)))", "AnyPromise(1)") XCTAssertEqual("\(AnyPromise(Promise.value(nil)))", "AnyPromise(nil)") } } ================================================ FILE: Tests/CoreObjC/HangTests.m ================================================ @import PromiseKit; @import XCTest; @interface HangTests: XCTestCase @end @implementation HangTests - (void)test { __block int x = 0; id value = PMKHang(PMKAfter(0.02).then(^{ x++; return 1; })); XCTAssertEqual(x, 1); XCTAssertEqualObjects(value, @1); } @end ================================================ FILE: Tests/CoreObjC/JoinTests.m ================================================ @import Foundation; @import PromiseKit; @import XCTest; @interface JoinTests: XCTestCase @end @implementation JoinTests - (void)test_73_join { XCTestExpectation *ex1 = [self expectationWithDescription:@""]; __block void (^fulfiller)(id) = nil; AnyPromise *promise = [AnyPromise promiseWithResolverBlock:^(PMKResolver resolve) { fulfiller = resolve; }]; PMKJoin(@[ [AnyPromise promiseWithValue:[NSError errorWithDomain:@"dom" code:1 userInfo:nil]], promise, [AnyPromise promiseWithValue:[NSError errorWithDomain:@"dom" code:2 userInfo:nil]] ]).then(^{ XCTFail(); }).catch(^(NSError *error){ id promises = error.userInfo[PMKJoinPromisesKey]; int cume = 0, cumv = 0; for (AnyPromise *promise in promises) { if ([promise.value isKindOfClass:[NSError class]]) { cume |= [promise.value code]; } else { cumv |= [promise.value unsignedIntValue]; } } XCTAssertTrue(cumv == 4); XCTAssertTrue(cume == 3); [ex1 fulfill]; }); fulfiller(@4); [self waitForExpectationsWithTimeout:1 handler:nil]; } - (void)test_74_join_no_errors { XCTestExpectation *ex1 = [self expectationWithDescription:@""]; PMKJoin(@[ [AnyPromise promiseWithValue:@1], [AnyPromise promiseWithValue:@2] ]).then(^(NSArray *values, id errors) { XCTAssertEqualObjects(values, (@[@1, @2])); XCTAssertNil(errors); [ex1 fulfill]; }); [self waitForExpectationsWithTimeout:1 handler:nil]; } - (void)test_75_join_no_success { XCTestExpectation *ex1 = [self expectationWithDescription:@""]; PMKJoin(@[ [AnyPromise promiseWithValue:[NSError errorWithDomain:@"dom" code:1 userInfo:nil]], [AnyPromise promiseWithValue:[NSError errorWithDomain:@"dom" code:2 userInfo:nil]], ]).then(^{ XCTFail(); }).catch(^(NSError *error){ XCTAssertNotNil(error.userInfo[PMKJoinPromisesKey]); [ex1 fulfill]; }); [self waitForExpectationsWithTimeout:1 handler:nil]; } - (void)test_76_join_fulfills_if_empty_input { XCTestExpectation *ex1 = [self expectationWithDescription:@""]; PMKJoin(@[]).then(^(id a, id b, id c){ XCTAssertEqualObjects(@[], a); XCTAssertNil(b); XCTAssertNil(c); [ex1 fulfill]; }); [self waitForExpectationsWithTimeout:1 handler:nil]; } - (void)test_join_nil { NSArray *foo = nil; NSError *err = PMKJoin(foo).value; XCTAssertEqual(err.domain, PMKErrorDomain); XCTAssertEqual(err.code, PMKInvalidUsageError); } @end ================================================ FILE: Tests/CoreObjC/PMKManifoldTests.m ================================================ @import PromiseKit; @import XCTest; @interface PMKManifoldTests: XCTestCase @end @implementation PMKManifoldTests - (void)test_62_access_extra_elements { id ex1 = [self expectationWithDescription:@""]; [AnyPromise promiseWithResolverBlock:^(PMKResolver resolve) { resolve(PMKManifold(@1)); }].then(^(id o, id m, id n){ XCTAssertNil(m, @"Accessing extra elements should not crash"); XCTAssertNil(n, @"Accessing extra elements should not crash"); XCTAssertEqualObjects(o, @1); [ex1 fulfill]; }); [self waitForExpectationsWithTimeout:1 handler:nil]; } - (void)test_63_then_manifold { id ex1 = [self expectationWithDescription:@""]; [AnyPromise promiseWithValue:@0].then(^{ return PMKManifold(@1, @2, @3); }).then(^(id o1, id o2, id o3){ XCTAssertEqualObjects(o1, @1); XCTAssertEqualObjects(o2, @2); XCTAssertEqualObjects(o3, @3); [ex1 fulfill]; }); [self waitForExpectationsWithTimeout:1 handler:nil]; } - (void)test_63_then_manifold_with_nil { id ex1 = [self expectationWithDescription:@""]; [AnyPromise promiseWithValue:@0].then(^{ return PMKManifold(@1, nil, @3); }).then(^(id o1, id o2, id o3){ XCTAssertEqualObjects(o1, @1); XCTAssertEqualObjects(o2, nil); XCTAssertEqualObjects(o3, @3); [ex1 fulfill]; }); [self waitForExpectationsWithTimeout:1 handler:nil]; } - (void)test_65_manifold_fulfill_value { id ex1 = [self expectationWithDescription:@""]; AnyPromise *promise = [AnyPromise promiseWithValue:@1].then(^{ return PMKManifold(@123, @2); }); promise.then(^(id a, id b){ XCTAssertNotNil(a); XCTAssertNotNil(b); [ex1 fulfill]; }); [self waitForExpectationsWithTimeout:1 handler:nil]; XCTAssertEqualObjects(promise.value, @123); } - (void)test_37_PMKMany_2 { id ex1 = [self expectationWithDescription:@""]; PMKAfter(0.02).then(^{ return PMKManifold(@1, @2); }).then(^(id a, id b){ XCTAssertEqualObjects(a, @1); XCTAssertEqualObjects(b, @2); [ex1 fulfill]; }); [self waitForExpectationsWithTimeout:1 handler:nil]; } @end ================================================ FILE: Tests/CoreObjC/RaceTests.m ================================================ @import Foundation; @import PromiseKit; @import XCTest; #define PMKTestErrorDomain @"PMKTestErrorDomain" static inline NSError *dummyWithCode(NSInteger code) { return [NSError errorWithDomain:PMKTestErrorDomain code:rand() userInfo:@{NSLocalizedDescriptionKey: @(code).stringValue}]; } @interface RaceTests : XCTestCase @end @implementation RaceTests - (void)test_race { id ex = [self expectationWithDescription:@""]; id p = PMKAfter(0.1).then(^{ return @2; }); PMKRace(@[PMKAfter(10), PMKAfter(20), p]).then(^(id obj){ XCTAssertEqual(2, [obj integerValue]); [ex fulfill]; }); [self waitForExpectationsWithTimeout:1 handler:nil]; } - (void)test_race_empty { id ex = [self expectationWithDescription:@""]; PMKRace(@[]).then(^(NSArray* array){ XCTFail(); [ex fulfill]; }).catch(^(NSError *e){ XCTAssertEqual(e.domain, PMKErrorDomain); XCTAssertEqual(e.code, PMKInvalidUsageError); XCTAssertEqualObjects(e.userInfo[NSLocalizedDescriptionKey], @"PMKRace(nil)"); [ex fulfill]; }); [self waitForExpectationsWithTimeout:1 handler:nil]; } - (void)test_race_fullfilled { id ex = [self expectationWithDescription:@""]; NSArray* promises = @[ PMKAfter(1).then(^{ return dummyWithCode(1); }), PMKAfter(2).then(^{ return dummyWithCode(2); }), PMKAfter(5).then(^{ return @1; }), PMKAfter(4).then(^{ return @2; }), PMKAfter(3).then(^{ return dummyWithCode(3); }) ]; PMKRaceFulfilled(promises).then(^(id obj){ XCTAssertEqual(2, [obj integerValue]); [ex fulfill]; }).catch(^{ XCTFail(); [ex fulfill]; }); [self waitForExpectationsWithTimeout:10 handler:nil]; } - (void)test_race_fulfilled_empty { id ex = [self expectationWithDescription:@""]; PMKRaceFulfilled(@[]).then(^(NSArray* array){ XCTFail(); [ex fulfill]; }).catch(^(NSError *e){ XCTAssertEqual(e.domain, PMKErrorDomain); XCTAssertEqual(e.code, PMKInvalidUsageError); XCTAssertEqualObjects(e.userInfo[NSLocalizedDescriptionKey], @"PMKRaceFulfilled(nil)"); [ex fulfill]; }); [self waitForExpectationsWithTimeout:1 handler:nil]; } - (void)test_race_fullfilled_with_no_winner { id ex = [self expectationWithDescription:@""]; NSArray* promises = @[ PMKAfter(1).then(^{ return dummyWithCode(1); }), PMKAfter(2).then(^{ return dummyWithCode(2); }), PMKAfter(3).then(^{ return dummyWithCode(3); }) ]; PMKRaceFulfilled(promises).then(^(id obj){ XCTFail(); [ex fulfill]; }).catch(^(NSError *e){ XCTAssertEqual(e.domain, PMKErrorDomain); XCTAssertEqual(e.code, PMKNoWinnerError); XCTAssertEqualObjects(e.userInfo[NSLocalizedDescriptionKey], @"PMKRaceFulfilled(nil)"); [ex fulfill]; }); [self waitForExpectationsWithTimeout:10 handler:nil]; } @end ================================================ FILE: Tests/CoreObjC/WhenTests.m ================================================ @import Foundation; @import PromiseKit; @import XCTest; @interface WhenTests: XCTestCase @end @implementation WhenTests - (void)testProgress { id ex = [self expectationWithDescription:@""]; XCTAssertNil([NSProgress currentProgress]); id p1 = PMKAfter(0.01); id p2 = PMKAfter(0.02); id p3 = PMKAfter(0.03); id p4 = PMKAfter(0.04); NSProgress *progress = [NSProgress progressWithTotalUnitCount:1]; [progress becomeCurrentWithPendingUnitCount:1]; PMKWhen(@[p1, p2, p3, p4]).then(^{ XCTAssertEqual(progress.completedUnitCount, 1); [ex fulfill]; }); [progress resignCurrent]; [self waitForExpectationsWithTimeout:5 handler:nil]; } - (void)testProgressDoesNotExceed100Percent { id ex1 = [self expectationWithDescription:@""]; id ex2 = [self expectationWithDescription:@""]; XCTAssertNil([NSProgress currentProgress]); id p1 = PMKAfter(0.01); id p2 = PMKAfter(0.02).then(^{ return [NSError errorWithDomain:@"a" code:1 userInfo:nil]; }); id p3 = PMKAfter(0.03); id p4 = PMKAfter(0.04); id promises = @[p1, p2, p3, p4]; NSProgress *progress = [NSProgress progressWithTotalUnitCount:1]; [progress becomeCurrentWithPendingUnitCount:1]; PMKWhen(promises).catch(^{ [ex2 fulfill]; }); [progress resignCurrent]; PMKJoin(promises).catch(^{ XCTAssertLessThanOrEqual(1, progress.fractionCompleted); XCTAssertEqual(progress.completedUnitCount, 1); [ex1 fulfill]; }); [self waitForExpectationsWithTimeout:1 handler:nil]; } - (void)testWhenManifolds { id ex = [self expectationWithDescription:@""]; id p1 = dispatch_promise(^{ return PMKManifold(@1, @2); }); id p2 = dispatch_promise(^{}); PMKWhen(@[p1, p2]).then(^(NSArray *results){ XCTAssertEqualObjects(results[0], @1); XCTAssertEqualObjects(results[1], [NSNull null]); [ex fulfill]; }); [self waitForExpectationsWithTimeout:1 handler:nil]; } - (void)test_55_all_dictionary { id ex1 = [self expectationWithDescription:@""]; id promises = @{ @1: @2, @2: @"abc", @"a": PMKAfter(0.1).then(^{ return @"HI"; }) }; PMKWhen(promises).then(^(NSDictionary *dict){ XCTAssertEqual(dict.count, 3ul); XCTAssertEqualObjects(dict[@1], @2); XCTAssertEqualObjects(dict[@2], @"abc"); XCTAssertEqualObjects(dict[@"a"], @"HI"); [ex1 fulfill]; }); [self waitForExpectationsWithTimeout:1 handler:nil]; } - (void)test_56_empty_array_when { id ex1 = [self expectationWithDescription:@""]; PMKWhen(@[]).then(^(NSArray *array){ XCTAssertEqual(array.count, 0ul); [ex1 fulfill]; }); [self waitForExpectationsWithTimeout:1 handler:nil]; } - (void)test_57_empty_array_all { id ex1 = [self expectationWithDescription:@""]; PMKWhen(@[]).then(^(NSArray *array){ XCTAssertEqual(array.count, 0ul); [ex1 fulfill]; }); [self waitForExpectationsWithTimeout:1 handler:nil]; } - (void)test_18_when { id ex1 = [self expectationWithDescription:@""]; id a = PMKAfter(0.02).then(^{ return @345; }); id b = PMKAfter(0.03).then(^{ return @345; }); PMKWhen(@[a, b]).then(^(NSArray *objs){ XCTAssertEqual(objs.count, 2ul); XCTAssertEqualObjects(objs[0], objs[1]); [ex1 fulfill]; }); [self waitForExpectationsWithTimeout:1 handler:nil]; } - (void)test_21_recursive_when { id domain = @"sdjhfg"; id ex1 = [self expectationWithDescription:@""]; id a = PMKAfter(0.03).then(^{ return [NSError errorWithDomain:domain code:123 userInfo:nil]; }); id b = PMKAfter(0.02); id c = PMKWhen(@[a, b]); PMKWhen(c).then(^{ XCTFail(); }).catch(^(NSError *e){ XCTAssertEqualObjects(e.userInfo[PMKFailingPromiseIndexKey], @0); XCTAssertEqualObjects(e.domain, domain); [ex1 fulfill]; }); [self waitForExpectationsWithTimeout:1 handler:nil]; } - (void)test_22_already_resolved_and_bubble { id ex1 = [self expectationWithDescription:@""]; id ex2 = [self expectationWithDescription:@""]; PMKResolver resolve; AnyPromise *promise = [[AnyPromise alloc] initWithResolver:&resolve]; promise.then(^{ XCTFail(); }).catch(^(NSError *e){ [ex1 fulfill]; }); resolve([NSError errorWithDomain:@"a" code:1 userInfo:nil]); PMKWhen(promise).then(^{ XCTFail(); }).catch(^{ [ex2 fulfill]; }); [self waitForExpectationsWithTimeout:1 handler:nil]; } - (void)test_24_some_edge_case { id ex1 = [self expectationWithDescription:@""]; id a = PMKAfter(0.02).catch(^{}); id b = PMKAfter(0.03); PMKWhen(@[a, b]).then(^(NSArray *objs){ [ex1 fulfill]; }); [self waitForExpectationsWithTimeout:1 handler:nil]; } - (void)test_35_when_nil { id ex1 = [self expectationWithDescription:@""]; AnyPromise *promise = [AnyPromise promiseWithValue:@"35"].then(^{ return nil; }); PMKWhen(@[PMKAfter(0.02).then(^{ return @1; }), [AnyPromise promiseWithValue:nil], promise]).then(^(NSArray *results){ XCTAssertEqual(results.count, 3ul); XCTAssertEqualObjects(results[1], [NSNull null]); [ex1 fulfill]; }).catch(^(NSError *err){ abort(); }); [self waitForExpectationsWithTimeout:1 handler:nil]; } - (void)test_39_when_with_some_values { id ex1 = [self expectationWithDescription:@""]; id p = PMKAfter(0.02); id v = @1; PMKWhen(@[p, v]).then(^(NSArray *aa){ XCTAssertEqual(aa.count, 2ul); XCTAssertEqualObjects(aa[1], @1); [ex1 fulfill]; }); [self waitForExpectationsWithTimeout:1 handler:nil]; } - (void)test_40_when_with_all_values { id ex1 = [self expectationWithDescription:@""]; PMKWhen(@[@1, @2]).then(^(NSArray *aa){ XCTAssertEqualObjects(aa[0], @1); XCTAssertEqualObjects(aa[1], @2); [ex1 fulfill]; }); [self waitForExpectationsWithTimeout:1 handler:nil]; } - (void)test_41_when_with_repeated_promises { id ex1 = [self expectationWithDescription:@""]; id p = PMKAfter(0.02); id v = @1; PMKWhen(@[p, v, p, v]).then(^(NSArray *aa){ XCTAssertEqual(aa.count, 4ul); XCTAssertEqualObjects(aa[1], @1); XCTAssertEqualObjects(aa[3], @1); [ex1 fulfill]; }); [self waitForExpectationsWithTimeout:1 handler:nil]; } - (void)test_45_when_which_returns_void { id ex1 = [self expectationWithDescription:@""]; AnyPromise *promise = [AnyPromise promiseWithValue:@1].then(^{}); PMKWhen(@[promise, [AnyPromise promiseWithValue:@1]]).then(^(NSArray *stuff){ XCTAssertEqual(stuff.count, 2ul); XCTAssertEqualObjects(stuff[0], [NSNull null]); [ex1 fulfill]; }); [self waitForExpectationsWithTimeout:1 handler:nil]; } - (void)test_when_nil { NSArray *foo = nil; NSError *err = PMKWhen(foo).value; XCTAssertEqual(err.domain, PMKErrorDomain); XCTAssertEqual(err.code, PMKInvalidUsageError); } - (void)test_when_bad_input { id foo = @"a"; XCTAssertEqual(PMKWhen(foo).value, foo); } @end ================================================ FILE: Tests/CorePromise/AfterTests.swift ================================================ import PromiseKit import XCTest class AfterTests: XCTestCase { func testZero() { let ex2 = expectation(description: "") after(seconds: 0).done(ex2.fulfill) waitForExpectations(timeout: 2, handler: nil) let ex3 = expectation(description: "") after(.seconds(0)).done(ex3.fulfill) waitForExpectations(timeout: 2, handler: nil) #if !SWIFT_PACKAGE let ex4 = expectation(description: "") __PMKAfter(0).done{ _ in ex4.fulfill() }.silenceWarning() waitForExpectations(timeout: 2, handler: nil) #endif } func testNegative() { let ex2 = expectation(description: "") after(seconds: -1).done(ex2.fulfill) waitForExpectations(timeout: 2, handler: nil) let ex3 = expectation(description: "") after(.seconds(-1)).done(ex3.fulfill) waitForExpectations(timeout: 2, handler: nil) #if !SWIFT_PACKAGE let ex4 = expectation(description: "") __PMKAfter(-1).done{ _ in ex4.fulfill() }.silenceWarning() waitForExpectations(timeout: 2, handler: nil) #endif } func testPositive() { let ex2 = expectation(description: "") after(seconds: 1).done(ex2.fulfill) waitForExpectations(timeout: 2, handler: nil) let ex3 = expectation(description: "") after(.seconds(1)).done(ex3.fulfill) waitForExpectations(timeout: 2, handler: nil) #if !SWIFT_PACKAGE let ex4 = expectation(description: "") __PMKAfter(1).done{ _ in ex4.fulfill() }.silenceWarning() waitForExpectations(timeout: 2, handler: nil) #endif } } ================================================ FILE: Tests/CorePromise/AsyncTests.swift ================================================ import PromiseKit import XCTest private enum Error: Swift.Error { case dummy } class AsyncTests: XCTestCase { #if swift(>=5.5) #if canImport(_Concurrency) @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *) func testAsyncPromiseValue() async throws { let promise = after(.milliseconds(100)).then(on: nil){ Promise.value(1) } let value = try await promise.async() XCTAssertEqual(value, 1) } @available(iOS, deprecated: 13.0) @available(macOS, deprecated: 10.15) @available(tvOS, deprecated: 13.0) @available(watchOS, deprecated: 6.0) func testAsyncPromiseValue() { } #else func testAsyncPromiseValue() { } #endif #else func testAsyncPromiseValue() { } #endif #if swift(>=5.5) #if canImport(_Concurrency) @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *) func testAsyncGuaranteeValue() async { let guarantee = after(.milliseconds(100)).then(on: nil){ Guarantee.value(1) } let value = await guarantee.async() XCTAssertEqual(value, 1) } @available(iOS, deprecated: 13.0) @available(macOS, deprecated: 10.15) @available(tvOS, deprecated: 13.0) @available(watchOS, deprecated: 6.0) func testAsyncGuaranteeValue() { } #else func testAsyncGuaranteeValue() { } #endif #else func testAsyncGuaranteeValue() { } #endif #if swift(>=5.5) #if canImport(_Concurrency) @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *) func testAsyncPromiseThrow() async throws { do { let promise = after(.milliseconds(100)).then(on: nil){ Promise(error: Error.dummy) }.then(on: nil){ Promise.value(1) } try await _ = promise.async() XCTAssert(false) } catch { switch error as? Error { case .dummy: XCTAssert(true) default: XCTAssert(false) } } } @available(iOS, deprecated: 13.0) @available(macOS, deprecated: 10.15) @available(tvOS, deprecated: 13.0) @available(watchOS, deprecated: 6.0) func testAsyncPromiseThrow() { } #else func testAsyncPromiseThrow() { } #endif #else func testAsyncPromiseThrow() { } #endif #if swift(>=5.5) #if canImport(_Concurrency) @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *) func testAsyncPromiseCancel() async throws { do { let p = after(seconds: 0).done { _ in throw LocalError.cancel }.done { XCTFail() } p.catch { _ in XCTFail() } try await p.async() XCTAssert(false) } catch { guard let cancellableError = error as? CancellableError else { return XCTFail("Unexpected error type") } XCTAssertTrue(cancellableError.isCancelled) } } @available(iOS, deprecated: 13.0) @available(macOS, deprecated: 10.15) @available(tvOS, deprecated: 13.0) @available(watchOS, deprecated: 6.0) func testAsyncPromiseCancel() { } #else func testAsyncPromiseCancel() { } #endif #else func testAsyncPromiseCancel() { } #endif } private enum LocalError: CancellableError { case notCancel case cancel var isCancelled: Bool { switch self { case .notCancel: return false case .cancel: return true } } } ================================================ FILE: Tests/CorePromise/CancellableErrorTests.swift ================================================ import Foundation import PromiseKit import XCTest #if canImport(StoreKit) import StoreKit #endif class CancellationTests: XCTestCase { func testCancellation() { let ex1 = expectation(description: "") let p = after(seconds: 0).done { _ in throw LocalError.cancel }.done { XCTFail() } p.catch { _ in XCTFail() } p.catch(policy: .allErrors) { XCTAssertTrue($0.isCancelled) ex1.fulfill() } waitForExpectations(timeout: 60) } func testThrowCancellableErrorThatIsNotCancelled() { let expct = expectation(description: "") after(seconds: 0).done { _ in throw LocalError.notCancel }.done { XCTFail() }.catch { XCTAssertFalse($0.isCancelled) expct.fulfill() } waitForExpectations(timeout: 1) } func testRecoverWithCancellation() { let ex1 = expectation(description: "") let ex2 = expectation(description: "") let p = after(seconds: 0).done { _ in throw CocoaError.cancelled }.recover(policy: .allErrors) { err -> Promise in ex1.fulfill() XCTAssertTrue(err.isCancelled) throw err }.done { _ in XCTFail() } p.catch { _ in XCTFail() } p.catch(policy: .allErrors) { XCTAssertTrue($0.isCancelled) ex2.fulfill() } waitForExpectations(timeout: 1) } func testFoundationBridging1() { let ex = expectation(description: "") let p = after(seconds: 0).done { _ in throw CocoaError.cancelled } p.catch { _ in XCTFail() } p.catch(policy: .allErrors) { XCTAssertTrue($0.isCancelled) ex.fulfill() } waitForExpectations(timeout: 1) } func testFoundationBridging2() { let ex = expectation(description: "") let p = Promise().done { throw URLError.cancelled } p.catch { _ in XCTFail() } p.catch(policy: .allErrors) { XCTAssertTrue($0.isCancelled) ex.fulfill() } waitForExpectations(timeout: 1) } func testDoesntCrashSwift() { #if canImport(StoreKit) if #available(watchOS 6.2, *) { do { let err = SKError(.paymentCancelled) XCTAssertTrue(err.isCancelled) throw err } catch { XCTAssertTrue(error.isCancelled) } XCTAssertFalse(SKError(.clientInvalid).isCancelled) } #endif } func testBridgeToNSError() { // Swift.Error types must be cast to NSError for the bridging to occur. // The below would throw an expection about an invalid selector without a cast: // `(error as AnyObject).value(forKey: "domain")` // This simply checks to make sure `isCancelled` is not making that mistake. class TestingError: Error { } XCTAssertFalse(TestingError().isCancelled) } #if swift(>=3.2) func testIsCancelled() { XCTAssertTrue(PMKError.cancelled.isCancelled) XCTAssertTrue(URLError.cancelled.isCancelled) XCTAssertTrue(CocoaError.cancelled.isCancelled) XCTAssertFalse(CocoaError(_nsError: NSError(domain: NSCocoaErrorDomain, code: CocoaError.Code.coderInvalidValue.rawValue)).isCancelled) } #endif } private enum LocalError: CancellableError { case notCancel case cancel var isCancelled: Bool { switch self { case .notCancel: return false case .cancel: return true } } } private extension URLError { static var cancelled: URLError { return .init(_nsError: NSError(domain: NSURLErrorDomain, code: URLError.Code.cancelled.rawValue)) } } private extension CocoaError { static var cancelled: CocoaError { return .init(_nsError: NSError(domain: NSCocoaErrorDomain, code: CocoaError.Code.userCancelled.rawValue)) } } ================================================ FILE: Tests/CorePromise/CatchableTests.swift ================================================ import PromiseKit import Dispatch import XCTest class CatchableTests: XCTestCase { func testFinally() { let finallyQueue = DispatchQueue(label: "\(#file):\(#line)", attributes: .concurrent) func helper(error: Error, on queue: DispatchQueue = .main, flags: DispatchWorkItemFlags? = nil) { let ex = (expectation(description: ""), expectation(description: "")) var x = 0 Promise(error: error).catch(policy: .allErrors) { _ in XCTAssertEqual(x, 0) x += 1 ex.0.fulfill() }.finally(on: queue, flags: flags) { if let flags = flags, flags.contains(.barrier) { dispatchPrecondition(condition: .onQueueAsBarrier(queue)) } else { dispatchPrecondition(condition: .onQueue(queue)) } XCTAssertEqual(x, 1) x += 1 ex.1.fulfill() } wait(for: [ex.0, ex.1], timeout: 10) } helper(error: Error.dummy) helper(error: Error.cancelled) helper(error: Error.dummy, on: finallyQueue) helper(error: Error.dummy, on: finallyQueue, flags: .barrier) } func testCauterize() { let ex = expectation(description: "") let p = Promise(error: Error.dummy) // cannot test specifically that this outputs to console, // but code-coverage will note that the line is run p.cauterize() p.catch { _ in ex.fulfill() } wait(for: [ex], timeout: 1) } } /// `Promise.recover` extension CatchableTests { func test__void_specialized_full_recover() { func helper(error: Swift.Error) { let ex = expectation(description: "") Promise(error: error).recover { _ in }.done(ex.fulfill) wait(for: [ex], timeout: 10) } helper(error: Error.dummy) helper(error: Error.cancelled) } func test__void_specialized_full_recover__fulfilled_path() { let ex = expectation(description: "") Promise().recover { _ in XCTFail() }.done(ex.fulfill) wait(for: [ex], timeout: 10) } func test__void_specialized_conditional_recover() { func helper(policy: CatchPolicy, error: Swift.Error, line: UInt = #line) { let ex = expectation(description: "") var x = 0 Promise(error: error).recover(policy: policy) { err in guard x < 1 else { throw err } x += 1 }.done(ex.fulfill).silenceWarning() wait(for: [ex], timeout: 10) } for error in [Error.dummy as Swift.Error, Error.cancelled] { helper(policy: .allErrors, error: error) } helper(policy: .allErrorsExceptCancellation, error: Error.dummy) } func test__void_specialized_conditional_recover__no_recover() { func helper(policy: CatchPolicy, error: Error, line: UInt = #line) { let ex = expectation(description: "") Promise(error: error).recover(policy: policy) { err in throw err }.catch(policy: .allErrors) { XCTAssertEqual(error, $0 as? Error) ex.fulfill() } wait(for: [ex], timeout: 10) } for error in [Error.dummy, Error.cancelled] { helper(policy: .allErrors, error: error) } helper(policy: .allErrorsExceptCancellation, error: Error.dummy) } func test__void_specialized_conditional_recover__ignores_cancellation_but_fed_cancellation() { let ex = expectation(description: "") Promise(error: Error.cancelled).recover(policy: .allErrorsExceptCancellation) { _ in XCTFail() }.catch(policy: .allErrors) { XCTAssertEqual(Error.cancelled, $0 as? Error) ex.fulfill() } wait(for: [ex], timeout: 10) } func test__void_specialized_conditional_recover__fulfilled_path() { let ex = expectation(description: "") Promise().recover { _ in XCTFail() }.catch { _ in XCTFail() // this `catch` to ensure we are calling the `recover` variant we think we are }.finally { ex.fulfill() } wait(for: [ex], timeout: 10) } } /// `Promise.recover` extension CatchableTests { func test__full_recover() { func helper(error: Swift.Error) { let ex = expectation(description: "") Promise(error: error).recover { _ in return .value(2) }.done { XCTAssertEqual($0, 2) ex.fulfill() } wait(for: [ex], timeout: 10) } helper(error: Error.dummy) helper(error: Error.cancelled) } func test__full_recover__fulfilled_path() { let ex = expectation(description: "") Promise.value(1).recover { _ in XCTFail(); return .value(2) }.done{ XCTAssertEqual($0, 1) ex.fulfill() } wait(for: [ex], timeout: 10) } func test__conditional_recover() { func helper(policy: CatchPolicy, error: Swift.Error, line: UInt = #line) { let ex = expectation(description: "") var x = 0 Promise(error: error).recover(policy: policy) { err -> Promise in guard x < 1 else { throw err } x += 1 return .value(x) }.done { XCTAssertEqual($0, x) ex.fulfill() }.silenceWarning() wait(for: [ex], timeout: 10) } for error in [Error.dummy as Swift.Error, Error.cancelled] { helper(policy: .allErrors, error: error) } helper(policy: .allErrorsExceptCancellation, error: Error.dummy) } func test__conditional_recover__no_recover() { func helper(policy: CatchPolicy, error: Error, line: UInt = #line) { let ex = expectation(description: "") Promise(error: error).recover(policy: policy) { err -> Promise in throw err }.catch(policy: .allErrors) { XCTAssertEqual(error, $0 as? Error) ex.fulfill() } wait(for: [ex], timeout: 10) } for error in [Error.dummy, Error.cancelled] { helper(policy: .allErrors, error: error) } helper(policy: .allErrorsExceptCancellation, error: Error.dummy) } func test__conditional_recover__ignores_cancellation_but_fed_cancellation() { let ex = expectation(description: "") Promise(error: Error.cancelled).recover(policy: .allErrorsExceptCancellation) { _ -> Promise in XCTFail() return .value(1) }.catch(policy: .allErrors) { XCTAssertEqual(Error.cancelled, $0 as? Error) ex.fulfill() } wait(for: [ex], timeout: 10) } func test__conditional_recover__fulfilled_path() { let ex = expectation(description: "") Promise.value(1).recover { err -> Promise in XCTFail() throw err }.done { XCTAssertEqual($0, 1) ex.fulfill() }.catch { _ in XCTFail() // this `catch` to ensure we are calling the `recover` variant we think we are } wait(for: [ex], timeout: 10) } func testEnsureThen_Error() { let ex = expectation(description: "") Promise.value(1).done { XCTAssertEqual($0, 1) throw Error.dummy }.ensureThen { after(seconds: 0.01) }.catch { XCTAssertEqual(Error.dummy, $0 as? Error) }.finally { ex.fulfill() } wait(for: [ex], timeout: 10) } func testEnsureThen_Value() { let ex = expectation(description: "") Promise.value(1).ensureThen { after(seconds: 0.01) }.done { XCTAssertEqual($0, 1) }.catch { _ in XCTFail() }.finally { ex.fulfill() } wait(for: [ex], timeout: 10) } } private enum Error: CancellableError { case dummy case cancelled var isCancelled: Bool { return self == Error.cancelled } } ================================================ FILE: Tests/CorePromise/CombineTests.swift ================================================ #if swift(>=4.1) #if canImport(Combine) import Combine #endif #endif import PromiseKit import XCTest private enum Error: Swift.Error { case dummy } class CombineTests: XCTestCase { private var cancellable: Any? override func tearDown() { #if swift(>=4.1) #if canImport(Combine) if #available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *) { (cancellable as? AnyCancellable)?.cancel() } #endif #endif } func testCombinePromiseValue() { let ex = expectation(description: "") #if swift(>=4.1) #if canImport(Combine) if #available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *) { let promise = after(.milliseconds(100)).then(on: nil){ Promise.value(1) } cancellable = promise.future().sink(receiveCompletion: { result in switch result { case .failure: XCTAssert(false) default: XCTAssert(true) } }, receiveValue: { XCTAssertEqual($0, 1) ex.fulfill() }) } else { ex.fulfill() } #else ex.fulfill() #endif #else ex.fulfill() #endif wait(for: [ex], timeout: 1) } func testCombineGuaranteeValue() { let ex = expectation(description: "") #if swift(>=4.1) #if canImport(Combine) if #available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *) { let promise = after(.milliseconds(100)).then(on: nil){ Guarantee.value(1) } cancellable = promise.future().sink(receiveCompletion: { result in switch result { case .failure: XCTAssert(false) default: XCTAssert(true) } }, receiveValue: { XCTAssertEqual($0, 1) ex.fulfill() }) } else { ex.fulfill() } #else ex.fulfill() #endif #else ex.fulfill() #endif wait(for: [ex], timeout: 1) } func testCombinePromiseThrow() { let ex = expectation(description: "") #if swift(>=4.1) #if canImport(Combine) if #available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *) { let promise = after(.milliseconds(100)).then(on: nil){ Promise(error: Error.dummy) }.then(on: nil){ Promise.value(1) } cancellable = promise.future().sink(receiveCompletion: { result in switch result { case .failure(let error): switch error as? Error { case .dummy: XCTAssert(true) default: XCTAssert(false) } default: XCTAssert(false) } ex.fulfill() }, receiveValue: { _ in XCTAssert(false) }) } else { ex.fulfill() } #else ex.fulfill() #endif #else ex.fulfill() #endif wait(for: [ex], timeout: 1) } func testPromiseCombineValue() { let ex = expectation(description: "") #if swift(>=4.1) #if canImport(Combine) if #available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *) { let promise = Future { resolver in resolver(.success(1)) }.delay(for: 5, scheduler: RunLoop.main).future().promise() promise.done { XCTAssertEqual($0, 1) ex.fulfill() }.catch { _ in XCTAssert(false) ex.fulfill() } } else { ex.fulfill() } #else ex.fulfill() #endif #else ex.fulfill() #endif wait(for: [ex], timeout: 10) } func testGuaranteeCombineValue() { let ex = expectation(description: "") #if swift(>=4.1) #if canImport(Combine) if #available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *) { let guarantee = Future { resolver in resolver(.success(1)) }.delay(for: 5, scheduler: RunLoop.main).future().guarantee() guarantee.done { XCTAssertEqual($0, 1) ex.fulfill() } } else { ex.fulfill() } #else ex.fulfill() #endif #else ex.fulfill() #endif wait(for: [ex], timeout: 10) } func testPromiseCombineThrows() { let ex = expectation(description: "") #if swift(>=4.1) #if canImport(Combine) if #available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *) { let promise = Future { resolver in resolver(.failure(.dummy)) }.delay(for: 5, scheduler: RunLoop.main).map { _ in 100 }.future().promise() promise.done { _ in XCTAssert(false) ex.fulfill() }.catch { error in switch error as? Error { case .dummy: XCTAssert(true) default: XCTAssert(false) } ex.fulfill() } } else { ex.fulfill() } #else ex.fulfill() #endif #else ex.fulfill() #endif wait(for: [ex], timeout: 10) } } #if swift(>=4.1) #if canImport(Combine) /// https://stackoverflow.com/a/60444607/2229783 @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *) private extension Publisher { func future() -> Future { return Future { promise in var ticket: AnyCancellable? = nil ticket = sink( receiveCompletion: { ticket?.cancel() ticket = nil switch $0 { case .failure(let error): promise(.failure(error)) case .finished: break } }, receiveValue: { ticket?.cancel() ticket = nil promise(.success($0)) } ) } } } #endif #endif ================================================ FILE: Tests/CorePromise/DefaultDispatchQueueTests.swift ================================================ // // PMKDefaultDispatchQueue.test.swift // PromiseKit // // Created by David Rodriguez on 4/14/16. // Copyright © 2016 Max Howell. All rights reserved. // import class Foundation.Thread import PromiseKit import Dispatch import XCTest private enum Error: Swift.Error { case dummy } class PMKDefaultDispatchQueueTest: XCTestCase { let myQueue = DispatchQueue(label: "myQueue") override func setUp() { // can actually only set the default queue once // - See: PMKSetDefaultDispatchQueue conf.Q = (myQueue, myQueue) } override func tearDown() { conf.Q = (.main, .main) } func testOverrodeDefaultThenQueue() { let ex = expectation(description: "resolving") Promise.value(1).then { _ -> Promise in ex.fulfill() XCTAssertFalse(Thread.isMainThread) return Promise() }.silenceWarning() XCTAssertTrue(Thread.isMainThread) waitForExpectations(timeout: 1) } func testOverrodeDefaultCatchQueue() { let ex = expectation(description: "resolving") Promise(error: Error.dummy).catch { _ in ex.fulfill() XCTAssertFalse(Thread.isMainThread) } XCTAssertTrue(Thread.isMainThread) waitForExpectations(timeout: 1) } func testOverrodeDefaultAlwaysQueue() { let ex = expectation(description: "resolving") Promise.value(1).ensure { ex.fulfill() XCTAssertFalse(Thread.isMainThread) }.silenceWarning() XCTAssertTrue(Thread.isMainThread) waitForExpectations(timeout: 1) } } ================================================ FILE: Tests/CorePromise/ErrorTests.swift ================================================ import PromiseKit import XCTest class PMKErrorTests: XCTestCase { func testCustomStringConvertible() { XCTAssertNotNil(PMKError.invalidCallingConvention.errorDescription) XCTAssertNotNil(PMKError.returnedSelf.errorDescription) XCTAssertNotNil(PMKError.badInput.errorDescription) XCTAssertNotNil(PMKError.cancelled.errorDescription) XCTAssertNotNil(PMKError.compactMap(1, Int.self).errorDescription) XCTAssertNotNil(PMKError.emptySequence.errorDescription) } func testCustomDebugStringConvertible() { XCTAssertFalse(PMKError.invalidCallingConvention.debugDescription.isEmpty) XCTAssertFalse(PMKError.returnedSelf.debugDescription.isEmpty) XCTAssertNotNil(PMKError.badInput.debugDescription.isEmpty) XCTAssertFalse(PMKError.cancelled.debugDescription.isEmpty) XCTAssertFalse(PMKError.compactMap(1, Int.self).debugDescription.isEmpty) XCTAssertFalse(PMKError.emptySequence.debugDescription.isEmpty) } } ================================================ FILE: Tests/CorePromise/GuaranteeTests.swift ================================================ import PromiseKit import XCTest class GuaranteeTests: XCTestCase { func testInit() { let ex = expectation(description: "") Guarantee { seal in seal(1) }.done { XCTAssertEqual(1, $0) ex.fulfill() } wait(for: [ex], timeout: 10) } func testMap() { let ex = expectation(description: "") Guarantee.value(1).map { $0 * 2 }.done { XCTAssertEqual(2, $0) ex.fulfill() } wait(for: [ex], timeout: 10) } func testMapByKeyPath() { let ex = expectation(description: "") Guarantee.value(Person(name: "Max")).map(\.name).done { XCTAssertEqual("Max", $0) ex.fulfill() } wait(for: [ex], timeout: 10) } func testWait() { XCTAssertEqual(after(.milliseconds(100)).map(on: nil){ 1 }.wait(), 1) } func testMapValues() { let ex = expectation(description: "") Guarantee.value([1, 2, 3]) .mapValues { $0 * 2 } .done { values in XCTAssertEqual([2, 4, 6], values) ex.fulfill() } wait(for: [ex], timeout: 10) } func testMapValuesByKeyPath() { let ex = expectation(description: "") Guarantee.value([Person(name: "Max"), Person(name: "Roman"), Person(name: "John")]) .mapValues(\.name) .done { values in XCTAssertEqual(["Max", "Roman", "John"], values) ex.fulfill() } wait(for: [ex], timeout: 10) } func testFlatMapValues() { let ex = expectation(description: "") Guarantee.value([1, 2, 3]) .flatMapValues { [$0, $0] } .done { values in XCTAssertEqual([1, 1, 2, 2, 3, 3], values) ex.fulfill() } wait(for: [ex], timeout: 10) } func testCompactMapValues() { let ex = expectation(description: "") Guarantee.value(["1","2","a","3"]) .compactMapValues { Int($0) } .done { values in XCTAssertEqual([1, 2, 3], values) ex.fulfill() } wait(for: [ex], timeout: 10) } func testCompactMapValuesByKeyPath() { let ex = expectation(description: "") Guarantee.value([Person(name: "Max"), Person(name: "Roman", age: 26), Person(name: "John", age: 23)]) .compactMapValues(\.age) .done { values in XCTAssertEqual([26, 23], values) ex.fulfill() } wait(for: [ex], timeout: 10) } func testThenMap() { let ex = expectation(description: "") Guarantee.value([1, 2, 3]) .thenMap { Guarantee.value($0 * 2) } .done { values in XCTAssertEqual([2, 4, 6], values) ex.fulfill() } wait(for: [ex], timeout: 10) } func testThenFlatMap() { let ex = expectation(description: "") Guarantee.value([1, 2, 3]) .thenFlatMap { Guarantee.value([$0, $0]) } .done { values in XCTAssertEqual([1, 1, 2, 2, 3, 3], values) ex.fulfill() } wait(for: [ex], timeout: 10) } func testFilterValues() { let ex = expectation(description: "") Guarantee.value([1, 2, 3]) .filterValues { $0 > 1 } .done { values in XCTAssertEqual([2, 3], values) ex.fulfill() } wait(for: [ex], timeout: 10) } func testFilterValuesByKeyPath() { let ex = expectation(description: "") Guarantee.value([Person(name: "Max"), Person(name: "Roman", age: 26, isStudent: false), Person(name: "John", age: 23, isStudent: true)]) .filterValues(\.isStudent) .done { values in XCTAssertEqual([Person(name: "John", age: 23, isStudent: true)], values) ex.fulfill() } wait(for: [ex], timeout: 10) } func testSorted() { let ex = expectation(description: "") Guarantee.value([5, 2, 3, 4, 1]) .sortedValues() .done { values in XCTAssertEqual([1, 2, 3, 4, 5], values) ex.fulfill() } wait(for: [ex], timeout: 10) } func testSortedBy() { let ex = expectation(description: "") Guarantee.value([5, 2, 3, 4, 1]) .sortedValues { $0 > $1 } .done { values in XCTAssertEqual([5, 4, 3, 2, 1], values) ex.fulfill() } wait(for: [ex], timeout: 10) } #if swift(>=3.1) func testNoAmbiguityForValue() { let ex = expectation(description: "") let a = Guarantee.value let b = Guarantee.value(Void()) let c = Guarantee.value(()) when(fulfilled: a, b, c).done { ex.fulfill() }.cauterize() wait(for: [ex], timeout: 10) } #endif } ================================================ FILE: Tests/CorePromise/HangTests.swift ================================================ import PromiseKit import XCTest class HangTests: XCTestCase { func test() { let ex = expectation(description: "block executed") do { let value = try hang(after(seconds: 0.02).then { _ -> Promise in ex.fulfill() return .value(1) }) XCTAssertEqual(value, 1) } catch { XCTFail("Unexpected error") } waitForExpectations(timeout: 0) } enum Error: Swift.Error { case test } func testError() { var value = 0 do { _ = try hang(after(seconds: 0.02).done { value = 1 throw Error.test }) XCTAssertEqual(value, 1) } catch Error.test { return } catch { XCTFail("Unexpected error (expected Error.test)") } XCTFail("Expected error but no error was thrown") } } ================================================ FILE: Tests/CorePromise/LoggingTests.swift ================================================ @testable import PromiseKit import Dispatch import XCTest #if canImport(Android) import Android #endif class LoggingTests: XCTestCase { /** The test should emit the following log messages: PromiseKit: warning: `wait()` called on main thread! PromiseKit: warning: pending promise deallocated PromiseKit:cauterized-error: purposes This is an error message */ func testLogging() { var logOutput: String? = nil enum ForTesting: Error { case purposes } // Test Logging to Console, the default behavior conf.logHandler(.waitOnMainThread) conf.logHandler(.pendingPromiseDeallocated) conf.logHandler(.pendingGuaranteeDeallocated) conf.logHandler(.cauterized(ForTesting.purposes)) XCTAssertNil(logOutput) // Now test no logging conf.logHandler = { event in } conf.logHandler(.waitOnMainThread) conf.logHandler(.pendingPromiseDeallocated) conf.logHandler(.cauterized(ForTesting.purposes)) XCTAssertNil(logOutput) conf.logHandler = { event in switch event { case .waitOnMainThread, .pendingPromiseDeallocated, .pendingGuaranteeDeallocated: logOutput = "\(event)" case .cauterized: // Using an enum with associated value does not convert to a string properly in // earlier versions of swift logOutput = "cauterized" } } conf.logHandler(.waitOnMainThread) XCTAssertEqual(logOutput!, "waitOnMainThread") logOutput = nil conf.logHandler(.pendingPromiseDeallocated) XCTAssertEqual(logOutput!, "pendingPromiseDeallocated") logOutput = nil conf.logHandler(.cauterized(ForTesting.purposes)) XCTAssertEqual(logOutput!, "cauterized") } // Verify waiting on main thread in Promise is logged func testPromiseWaitOnMainThreadLogged() throws { enum ForTesting: Error { case purposes } var logOutput: String? = nil conf.logHandler = { event in logOutput = "\(event)" } let promiseResolver = Promise.pending() let workQueue = DispatchQueue(label: "worker") workQueue.async { promiseResolver.resolver.fulfill ("PromiseFulfilled") } let promisedString = try promiseResolver.promise.wait() XCTAssertEqual("PromiseFulfilled", promisedString) XCTAssertEqual(logOutput!, "waitOnMainThread") } // Verify Promise.cauterize() is logged func testCauterizeIsLogged() { enum ForTesting: Error { case purposes } var logOutput: String? = nil conf.logHandler = { event in switch event { case .waitOnMainThread, .pendingPromiseDeallocated, .pendingGuaranteeDeallocated: logOutput = "\(event)" case .cauterized: // Using an enum with associated value does not convert to a string properly in // earlier versions of swift logOutput = "cauterized" } } func createPromise() -> Promise { let promiseResolver = Promise.pending() let queue = DispatchQueue(label: "workQueue") queue.async { promiseResolver.resolver.reject(ForTesting.purposes) } return promiseResolver.promise } var ex = expectation(description: "cauterize") firstly { createPromise() }.ensure { ex.fulfill() }.cauterize() waitForExpectations(timeout: 1) ex = expectation(description: "read") let readQueue = DispatchQueue(label: "readQueue") readQueue.async { var outputSet = false while !outputSet { if let logOutput = logOutput { XCTAssertEqual(logOutput, "cauterized") outputSet = true ex.fulfill() } if !outputSet { usleep(10000) } } } waitForExpectations(timeout: 1) } // Verify waiting on main thread in Guarantee is logged func testGuaranteeWaitOnMainThreadLogged() { enum ForTesting: Error { case purposes } var logOutput: String? = nil conf.logHandler = { event in switch event { case .waitOnMainThread, .pendingPromiseDeallocated, .pendingGuaranteeDeallocated: logOutput = "\(event)" case .cauterized: // Using an enum with associated value does not convert to a string properly in // earlier versions of swift logOutput = "cauterized" } } let guaranteeResolve = Guarantee.pending() let workQueue = DispatchQueue(label: "worker") workQueue.async { guaranteeResolve.resolve("GuaranteeFulfilled") } let guaranteedString = guaranteeResolve.guarantee.wait() XCTAssertEqual("GuaranteeFulfilled", guaranteedString) XCTAssertEqual(logOutput!, "waitOnMainThread") } // Verify pendingPromiseDeallocated is logged func testPendingPromiseDeallocatedIsLogged() { var logOutput: String? = nil conf.logHandler = { event in switch event { case .waitOnMainThread, .pendingPromiseDeallocated, .pendingGuaranteeDeallocated: logOutput = "\(event)" case .cauterized: // Using an enum with associated value does not convert to a string properly in // earlier versions of swift logOutput = "cauterized" } } do { let _ = Promise.pending() } XCTAssertEqual ("pendingPromiseDeallocated", logOutput!) } // Verify pendingGuaranteeDeallocated is logged func testPendingGuaranteeDeallocatedIsLogged() { var logOutput: String? = nil let loggingClosure: (PromiseKit.LogEvent) -> Void = { event in switch event { case .waitOnMainThread, .pendingPromiseDeallocated, .pendingGuaranteeDeallocated: logOutput = "\(event)" case .cauterized: // Using an enum with associated value does not convert to a string properly in // earlier versions of swift logOutput = "cauterized" } } conf.logHandler = loggingClosure do { let _ = Guarantee.pending() } XCTAssertEqual ("pendingGuaranteeDeallocated", logOutput!) } //TODO Verify pending promise deallocation is logged } ================================================ FILE: Tests/CorePromise/PromiseTests.swift ================================================ import PromiseKit import Dispatch import XCTest class PromiseTests: XCTestCase { func testIsPending() { XCTAssertTrue(Promise.pending().promise.isPending) XCTAssertFalse(Promise().isPending) XCTAssertFalse(Promise(error: Error.dummy).isPending) } func testIsResolved() { XCTAssertFalse(Promise.pending().promise.isResolved) XCTAssertTrue(Promise().isResolved) XCTAssertTrue(Promise(error: Error.dummy).isResolved) } func testIsFulfilled() { XCTAssertFalse(Promise.pending().promise.isFulfilled) XCTAssertTrue(Promise().isFulfilled) XCTAssertFalse(Promise(error: Error.dummy).isFulfilled) } func testIsRejected() { XCTAssertFalse(Promise.pending().promise.isRejected) XCTAssertTrue(Promise(error: Error.dummy).isRejected) XCTAssertFalse(Promise().isRejected) } @available(macOS 10.10, iOS 2.0, tvOS 10.0, watchOS 2.0, *) func testDispatchQueueAsyncExtensionReturnsPromise() { let ex = expectation(description: "") DispatchQueue.global().async(.promise) { () -> Int in XCTAssertFalse(Thread.isMainThread) return 1 }.done { one in XCTAssertEqual(one, 1) ex.fulfill() } waitForExpectations(timeout: 1) } @available(macOS 10.10, iOS 2.0, tvOS 10.0, watchOS 2.0, *) func testDispatchQueueAsyncExtensionCanThrowInBody() { let ex = expectation(description: "") DispatchQueue.global().async(.promise) { () -> Int in throw Error.dummy }.done { _ in XCTFail() }.catch { _ in ex.fulfill() } waitForExpectations(timeout: 1) } func testCustomStringConvertible() { XCTAssertEqual(Promise.pending().promise.debugDescription, "Promise.pending(handlers: 0)") XCTAssertEqual(Promise().debugDescription, "Promise<()>.fulfilled(())") XCTAssertEqual(Promise(error: Error.dummy).debugDescription, "Promise.rejected(Error.dummy)") XCTAssertEqual("\(Promise.pending().promise)", "Promise(…Int)") XCTAssertEqual("\(Promise.value(3))", "Promise(3)") XCTAssertEqual("\(Promise(error: Error.dummy))", "Promise(dummy)") } func testCannotFulfillWithError() { // sadly this test proves the opposite :( // left here so maybe one day we can prevent instantiation of `Promise` _ = Promise { seal in seal.fulfill(Error.dummy) } _ = Promise.pending() _ = Promise.value(Error.dummy) _ = Promise().map { Error.dummy } } #if swift(>=3.1) func testCanMakeVoidPromise() { _ = Promise() _ = Guarantee() } #endif enum Error: Swift.Error { case dummy } func testThrowInInitializer() { let p = Promise { _ in throw Error.dummy } XCTAssertTrue(p.isRejected) guard let err = p.error, case Error.dummy = err else { return XCTFail() } } func testThrowInFirstly() { let ex = expectation(description: "") firstly { () -> Promise in throw Error.dummy }.catch { XCTAssertEqual($0 as? Error, Error.dummy) ex.fulfill() } wait(for: [ex], timeout: 10) } func testWait() throws { let p = after(.milliseconds(100)).then(on: nil){ Promise.value(1) } XCTAssertEqual(try p.wait(), 1) do { let p = after(.milliseconds(100)).map(on: nil){ throw Error.dummy } try p.wait() XCTFail() } catch { XCTAssertEqual(error as? Error, Error.dummy) } } func testPipeForResolved() { let ex = expectation(description: "") Promise.value(1).done { XCTAssertEqual(1, $0) ex.fulfill() }.silenceWarning() wait(for: [ex], timeout: 10) } #if swift(>=3.1) func testNoAmbiguityForValue() { let ex = expectation(description: "") let a = Promise.value let b = Promise.value(Void()) let c = Promise.value(()) when(fulfilled: a, b, c).done { ex.fulfill() }.cauterize() wait(for: [ex], timeout: 10) } #endif } ================================================ FILE: Tests/CorePromise/RaceTests.swift ================================================ import XCTest import PromiseKit class RaceTests: XCTestCase { func test1() { let ex = expectation(description: "") race(after(.milliseconds(10)).then{ Promise.value(1) }, after(seconds: 1).map{ 2 }).done { index in XCTAssertEqual(index, 1) ex.fulfill() }.silenceWarning() waitForExpectations(timeout: 1, handler: nil) } func test2() { let ex = expectation(description: "") race(after(seconds: 1).map{ 1 }, after(.milliseconds(10)).map{ 2 }).done { index in XCTAssertEqual(index, 2) ex.fulfill() } waitForExpectations(timeout: 1, handler: nil) } func test1Array() { let ex = expectation(description: "") let promises = [after(.milliseconds(10)).map{ 1 }, after(seconds: 1).map{ 2 }] race(promises).done { index in XCTAssertEqual(index, 1) ex.fulfill() }.silenceWarning() waitForExpectations(timeout: 1, handler: nil) } func test2Array() { let ex = expectation(description: "") race(after(seconds: 1).map{ 1 }, after(.milliseconds(10)).map{ 2 }).done { index in XCTAssertEqual(index, 2) ex.fulfill() } waitForExpectations(timeout: 1, handler: nil) } func testEmptyArray() { let ex = expectation(description: "") let empty = [Promise]() race(empty).catch { guard case PMKError.badInput = $0 else { return XCTFail() } ex.fulfill() } wait(for: [ex], timeout: 10) } func testFulfilled() { enum Error: Swift.Error { case test1, test2, test3 } let ex = expectation(description: "") let promises: [Promise] = [after(seconds: 1).map { _ in throw Error.test1 }, after(seconds: 2).map { _ in throw Error.test2 }, after(seconds: 5).map { 1 }, after(seconds: 4).map { 2 }, after(seconds: 3).map { _ in throw Error.test3 }] race(fulfilled: promises).done { XCTAssertEqual($0, 2) ex.fulfill() }.catch { _ in XCTFail() ex.fulfill() } wait(for: [ex], timeout: 10) } func testFulfilledEmptyArray() { let ex = expectation(description: "") let empty = [Promise]() race(fulfilled: empty).catch { guard case PMKError.badInput = $0 else { return XCTFail() } ex.fulfill() } wait(for: [ex], timeout: 10) } func testFulfilledWithNoWinner() { enum Error: Swift.Error { case test1, test2 } let ex = expectation(description: "") let promises: [Promise] = [ after(seconds: 1).map { _ in throw Error.test1 }, after(seconds: 2).map { _ in throw Error.test2 } ] race(fulfilled: promises).done { _ in XCTFail("Done with error") ex.fulfill() }.catch { guard let pmkError = $0 as? PMKError else { return XCTFail("error is not PMKError") } guard case .noWinner = pmkError else { return XCTFail("error is not .noWinner") } guard pmkError.debugDescription == "All thenables passed to race(fulfilled:) were rejected" else { return XCTFail("Not all thenables passed to race(fulfilled:) were rejected") } ex.fulfill() } wait(for: [ex], timeout: 10) } } ================================================ FILE: Tests/CorePromise/RegressionTests.swift ================================================ import PromiseKit import XCTest class RegressionTests: XCTestCase { func testReturningPreviousPromiseWorks() { // regression test because we were doing this wrong // in our A+ tests implementation for spec: 2.3.1 do { let promise1 = Promise() let promise2 = promise1.then(on: nil) { promise1 } promise2.catch(on: nil) { _ in XCTFail() } } do { enum Error: Swift.Error { case dummy } let promise1 = Promise(error: Error.dummy) let promise2 = promise1.recover(on: nil) { _ in promise1 } promise2.catch(on: nil) { err in if case PMKError.returnedSelf = err { XCTFail() } } } } } ================================================ FILE: Tests/CorePromise/ResolverTests.swift ================================================ import PromiseKit import XCTest class WrapTests: XCTestCase { fileprivate class KittenFetcher { let value: Int? let error: Error? init(value: Int?, error: Error?) { self.value = value self.error = error } func fetchWithCompletionBlock(block: @escaping(Int?, Error?) -> Void) { after(.milliseconds(20)).done { block(self.value, self.error) } } func fetchWithCompletionBlock2(block: @escaping(Error?, Int?) -> Void) { after(.milliseconds(20)).done { block(self.error, self.value) } } func fetchWithCompletionBlock3(block: @escaping(Int, Error?) -> Void) { after(.milliseconds(20)).done { block(self.value ?? -99, self.error) } } func fetchWithCompletionBlock4(block: @escaping(Error?) -> Void) { after(.milliseconds(20)).done { block(self.error) } } #if swift(>=5.0) func fetchWithCompletionBlock5(block: @escaping(Swift.Result) -> Void) { after(.milliseconds(20)).done { if let value = self.value { block(.success(value)) } else { block(.failure(self.error!)) } } } #endif } func testSuccess() { let ex = expectation(description: "") let kittenFetcher = KittenFetcher(value: 2, error: nil) Promise { seal in kittenFetcher.fetchWithCompletionBlock(block: seal.resolve) }.done { XCTAssertEqual($0, 2) ex.fulfill() }.silenceWarning() waitForExpectations(timeout: 1) } func testError() { let ex = expectation(description: "") let kittenFetcher = KittenFetcher(value: nil, error: Error.test) Promise { seal in kittenFetcher.fetchWithCompletionBlock(block: seal.resolve) }.catch { error in defer { ex.fulfill() } guard case Error.test = error else { return XCTFail() } } waitForExpectations(timeout: 1) } func testInvalidCallingConvention() { let ex = expectation(description: "") let kittenFetcher = KittenFetcher(value: nil, error: nil) Promise { seal in kittenFetcher.fetchWithCompletionBlock(block: seal.resolve) }.catch { error in defer { ex.fulfill() } guard case PMKError.invalidCallingConvention = error else { return XCTFail() } } waitForExpectations(timeout: 1) } func testInvertedCallingConvention() { let ex = expectation(description: "") let kittenFetcher = KittenFetcher(value: 2, error: nil) Promise { seal in kittenFetcher.fetchWithCompletionBlock2(block: seal.resolve) }.done { XCTAssertEqual($0, 2) ex.fulfill() }.silenceWarning() waitForExpectations(timeout: 1) } func testNonOptionalFirstParameter() { let ex1 = expectation(description: "") let kf1 = KittenFetcher(value: 2, error: nil) Promise { seal in kf1.fetchWithCompletionBlock3(block: seal.resolve) }.done { XCTAssertEqual($0, 2) ex1.fulfill() }.silenceWarning() let ex2 = expectation(description: "") let kf2 = KittenFetcher(value: -100, error: Error.test) Promise { seal in kf2.fetchWithCompletionBlock3(block: seal.resolve) }.catch { _ in ex2.fulfill() } wait(for: [ex1, ex2] ,timeout: 1) } #if swift(>=3.1) func testVoidCompletionValue() { let ex1 = expectation(description: "") let kf1 = KittenFetcher(value: nil, error: nil) Promise { seal in kf1.fetchWithCompletionBlock4(block: seal.resolve) }.done(ex1.fulfill).silenceWarning() let ex2 = expectation(description: "") let kf2 = KittenFetcher(value: nil, error: Error.test) Promise { seal in kf2.fetchWithCompletionBlock4(block: seal.resolve) }.catch { _ in ex2.fulfill() } wait(for: [ex1, ex2], timeout: 1) } #endif func testSwiftResultSuccess() { #if swift(>=5.0) let ex = expectation(description: "") let kittenFetcher = KittenFetcher(value: 2, error: nil) Promise { seal in kittenFetcher.fetchWithCompletionBlock5(block: seal.resolve) }.done { XCTAssertEqual($0, 2) ex.fulfill() }.silenceWarning() waitForExpectations(timeout: 1) #endif } func testSwiftResultError() { #if swift(>=5.0) let ex = expectation(description: "") let kittenFetcher = KittenFetcher(value: nil, error: Error.test) Promise { seal in kittenFetcher.fetchWithCompletionBlock5(block: seal.resolve) }.catch { error in defer { ex.fulfill() } guard case Error.test = error else { return XCTFail() } } waitForExpectations(timeout: 1) #endif } func testIsFulfilled() { XCTAssertTrue(Promise.value(()).result?.isFulfilled ?? false) XCTAssertFalse(Promise(error: Error.test).result?.isFulfilled ?? true) } func testPendingPromiseDeallocated() { // NOTE this doesn't seem to register the `deinit` as covered :( // BUT putting a breakpoint in the deinit CLEARLY shows it getting covered… class Foo { let p = Promise.pending() var ex: XCTestExpectation! deinit { after(.milliseconds(100)).done(ex.fulfill) } } let ex = expectation(description: "") do { // for code coverage report for `Resolver.deinit` warning let foo = Foo() foo.ex = ex } wait(for: [ex], timeout: 10) } func testVoidResolverFulfillAmbiguity() { #if !swift(>=5) && swift(>=4.1) || swift(>=3.3) && !swift(>=4.0) // ^^ this doesn’t work with Swift < 3.3 for some reason // ^^ this doesn’t work with Swift 5.0-beta1 for some reason // reference: https://github.com/mxcl/PromiseKit/issues/990 func foo(success: () -> Void, failure: (Error) -> Void) { success() } func bar() -> Promise { return Promise { (seal: Resolver) in foo(success: seal.fulfill, failure: seal.reject) } } let ex = expectation(description: "") bar().done(ex.fulfill).cauterize() wait(for: [ex], timeout: 10) #endif } } private enum Error: Swift.Error { case test } ================================================ FILE: Tests/CorePromise/StressTests.swift ================================================ import PromiseKit import Dispatch import XCTest class StressTests: XCTestCase { func testThenDataRace() { let e1 = expectation(description: "") //will crash if then doesn't protect handlers stressDataRace(expectation: e1, stressFunction: { promise in promise.done { s in XCTAssertEqual("ok", s) return }.silenceWarning() }, fulfill: { "ok" }) waitForExpectations(timeout: 10, handler: nil) } @available(macOS 10.10, iOS 2.0, tvOS 10.0, watchOS 2.0, *) func testThensAreSequentialForLongTime() { var values = [Int]() let ex = expectation(description: "") var promise = DispatchQueue.global().async(.promise){ 0 } let N = 1000 for x in 1.. Guarantee in values.append(y) XCTAssertEqual(x - 1, y) return DispatchQueue.global().async(.promise) { x } } } promise.done { x in values.append(x) XCTAssertEqual(values, (0..(expectation e1: XCTestExpectation, iterations: Int = 1000, stressFactor: Int = 10, stressFunction: @escaping (Promise) -> Void, fulfill f: @escaping () -> T) { let group = DispatchGroup() let queue = DispatchQueue(label: "the.domain.of.Zalgo", attributes: .concurrent) for _ in 0...pending() DispatchQueue.concurrentPerform(iterations: stressFactor) { n in stressFunction(promise) } queue.async(group: group) { seal.fulfill(f()) } } group.notify(queue: queue, execute: e1.fulfill) } ================================================ FILE: Tests/CorePromise/ThenableTests.swift ================================================ import PromiseKit import Dispatch import XCTest struct Person: Equatable { let name: String let age: Int? let isStudent: Bool init( name: String = "", age: Int? = nil, isStudent: Bool = false ) { self.name = name self.age = age self.isStudent = isStudent } } class ThenableTests: XCTestCase { func testGet() { let ex1 = expectation(description: "") let ex2 = expectation(description: "") Promise.value(1).get { XCTAssertEqual($0, 1) ex1.fulfill() }.done { XCTAssertEqual($0, 1) ex2.fulfill() }.silenceWarning() wait(for: [ex1, ex2], timeout: 10) } func testMap() { let ex = expectation(description: "") Promise.value(1).map { $0 * 2 }.done { XCTAssertEqual($0, 2) ex.fulfill() }.silenceWarning() wait(for: [ex], timeout: 10) } func testMapByKeyPath() { let ex = expectation(description: "") Promise.value(Person(name: "Max")).map(\.name).done { XCTAssertEqual($0, "Max") ex.fulfill() }.silenceWarning() wait(for: [ex], timeout: 10) } func testCompactMap() { let ex = expectation(description: "") Promise.value(1.0).compactMap { Int($0) }.done { XCTAssertEqual($0, 1) ex.fulfill() }.silenceWarning() wait(for: [ex], timeout: 10) } func testCompactMapThrows() { enum E: Error { case dummy } let ex = expectation(description: "") Promise.value("a").compactMap { x -> Int in throw E.dummy }.catch { if case E.dummy = $0 {} else { XCTFail() } ex.fulfill() } wait(for: [ex], timeout: 10) } func testRejectedPromiseCompactMap() { enum E: Error { case dummy } let ex = expectation(description: "") Promise(error: E.dummy).compactMap { Int($0) }.catch { if case E.dummy = $0 {} else { XCTFail() } ex.fulfill() } wait(for: [ex], timeout: 10) } func testPMKErrorCompactMap() { let ex = expectation(description: "") Promise.value("a").compactMap { Int($0) }.catch { if case PMKError.compactMap = $0 {} else { XCTFail() } ex.fulfill() } wait(for: [ex], timeout: 10) } func testCompactMapByKeyPath() { let ex = expectation(description: "") Promise.value(Person(name: "Roman", age: 26)).compactMap(\.age).done { XCTAssertEqual($0, 26) ex.fulfill() }.silenceWarning() wait(for: [ex], timeout: 10) } func testMapValues() { let ex = expectation(description: "") Promise.value([14, 20, 45]).mapValues { $0 * 2 }.done { XCTAssertEqual([28, 40, 90], $0) ex.fulfill() }.silenceWarning() wait(for: [ex], timeout: 10) } func testMapValuesByKeyPath() { let ex = expectation(description: "") Promise.value([Person(name: "Max"), Person(name: "Roman"), Person(name: "John")]).mapValues(\.name).done { XCTAssertEqual(["Max", "Roman", "John"], $0) ex.fulfill() }.silenceWarning() wait(for: [ex], timeout: 10) } func testCompactMapValues() { let ex = expectation(description: "") Promise.value(["1","2","a","4"]).compactMapValues { Int($0) }.done { XCTAssertEqual([1,2,4], $0) ex.fulfill() }.silenceWarning() wait(for: [ex], timeout: 10) } func testCompactMapValuesByKeyPath() { let ex = expectation(description: "") Promise.value([Person(name: "Max"), Person(name: "Roman", age: 26), Person(name: "John", age: 23)]).compactMapValues(\.age).done { XCTAssertEqual([26, 23], $0) ex.fulfill() }.silenceWarning() wait(for: [ex], timeout: 10) } func testThenMap() { let ex = expectation(description: "") Promise.value([1,2,3,4]).thenMap { Promise.value($0) }.done { XCTAssertEqual([1,2,3,4], $0) ex.fulfill() }.silenceWarning() wait(for: [ex], timeout: 10) } func testThenFlatMap() { let ex = expectation(description: "") Promise.value([1,2,3,4]).thenFlatMap { Promise.value([$0, $0]) }.done { XCTAssertEqual([1,1,2,2,3,3,4,4], $0) ex.fulfill() }.silenceWarning() wait(for: [ex], timeout: 10) } func testFilterValues() { let ex = expectation(description: "") Promise.value([Person(name: "Max"), Person(name: "Roman", age: 26, isStudent: false), Person(name: "John", age: 23, isStudent: true)]).filterValues { $0.isStudent }.done { XCTAssertEqual([Person(name: "John", age: 23, isStudent: true)], $0) ex.fulfill() }.silenceWarning() wait(for: [ex], timeout: 10) } func testFilterValuesByKeyPath() { let ex = expectation(description: "") Promise.value([Person(name: "Max"), Person(name: "Roman", age: 26, isStudent: false), Person(name: "John", age: 23, isStudent: true)]).filterValues(\.isStudent).done { XCTAssertEqual([Person(name: "John", age: 23, isStudent: true)], $0) ex.fulfill() }.silenceWarning() wait(for: [ex], timeout: 10) } func testLastValueForEmpty() { let values = [String]() XCTAssertTrue(Promise.value(values).lastValue.isRejected) } func testFirstValueForEmpty() { let values = [String]() XCTAssertTrue(Promise.value(values).firstValue.isRejected) } func testThenOffRejected() { // surprisingly missing in our CI, mainly due to // extensive use of `done` in A+ tests since PMK 5 let ex = expectation(description: "") Promise(error: PMKError.badInput).then { x -> Promise in XCTFail() return .value(x) }.catch { _ in ex.fulfill() } wait(for: [ex], timeout: 10) } func testBarrier() { let ex = expectation(description: "") let q = DispatchQueue(label: "\(#file):\(#line)", attributes: .concurrent) Promise.value(1).done(on: q, flags: .barrier) { XCTAssertEqual($0, 1) dispatchPrecondition(condition: .onQueueAsBarrier(q)) ex.fulfill() }.catch { _ in XCTFail() } wait(for: [ex], timeout: 10) } func testDispatchFlagsSyntax() { let ex = expectation(description: "") let q = DispatchQueue(label: "\(#file):\(#line)", attributes: .concurrent) Promise.value(1).done(on: q, flags: [.barrier, .inheritQoS]) { XCTAssertEqual($0, 1) dispatchPrecondition(condition: .onQueueAsBarrier(q)) ex.fulfill() }.catch { _ in XCTFail() } wait(for: [ex], timeout: 10) } } ================================================ FILE: Tests/CorePromise/Utilities.swift ================================================ import PromiseKit extension Promise { func silenceWarning() {} } #if os(Linux) || os(Android) import func CoreFoundation._CFIsMainThread extension Thread { // `isMainThread` is not implemented yet in swift-corelibs-foundation. static var isMainThread: Bool { return _CFIsMainThread() } } import XCTest extension XCTestCase { func wait(for: [XCTestExpectation], timeout: TimeInterval, file: StaticString = #file, line: UInt = #line) { #if !(swift(>=4.0) && !swift(>=4.1)) let line = Int(line) #endif waitForExpectations(timeout: timeout, file: file, line: line) } } extension XCTestExpectation { func fulfill() { fulfill(#file, line: #line) } } #endif ================================================ FILE: Tests/CorePromise/WhenConcurrentTests.swift ================================================ import XCTest import PromiseKit class WhenConcurrentTestCase_Swift: XCTestCase { func testWhen() { let e = expectation(description: "") var numbers = (0..<42).makeIterator() let squareNumbers = numbers.map { $0 * $0 } let generator = AnyIterator> { guard let number = numbers.next() else { return nil } return after(.milliseconds(10)).map { return number * number } } when(fulfilled: generator, concurrently: 5).done { numbers in if numbers == squareNumbers { e.fulfill() } }.silenceWarning() waitForExpectations(timeout: 3, handler: nil) } func testWhenEmptyGenerator() { let e = expectation(description: "") let generator = AnyIterator> { return nil } when(fulfilled: generator, concurrently: 5).done { numbers in if numbers.count == 0 { e.fulfill() } }.silenceWarning() waitForExpectations(timeout: 1, handler: nil) } func testWhenGeneratorError() { enum LocalError: Error { case Unknown case DivisionByZero } let expectedErrorIndex = 42 let expectedError = LocalError.DivisionByZero let e = expectation(description: "") var numbers = (-expectedErrorIndex..> { guard let number = numbers.next() else { return nil } return after(.milliseconds(10)).then { _ -> Promise in if number != 0 { return Promise(error: expectedError) } else { return .value(100500 / number) } } } when(fulfilled: generator, concurrently: 3) .catch { error in guard let error = error as? LocalError else { return } guard case .DivisionByZero = error else { return } e.fulfill() } waitForExpectations(timeout: 3, handler: nil) } func testWhenConcurrency() { let expectedConcurrently = 4 var currentConcurrently = 0 var maxConcurrently = 0 let e = expectation(description: "") var numbers = (0..<42).makeIterator() let generator = AnyIterator> { currentConcurrently += 1 maxConcurrently = max(maxConcurrently, currentConcurrently) guard let number = numbers.next() else { return nil } return after(.milliseconds(10)).then(on: .main) { _ -> Promise in currentConcurrently -= 1 return .value(number * number) } } when(fulfilled: generator, concurrently: expectedConcurrently).done { _ in XCTAssertEqual(expectedConcurrently, maxConcurrently) e.fulfill() }.silenceWarning() waitForExpectations(timeout: 3) } func testWhenConcurrencyLessThanZero() { let generator = AnyIterator> { XCTFail(); return nil } let p1 = when(fulfilled: generator, concurrently: 0) let p2 = when(fulfilled: generator, concurrently: -1) guard let e1 = p1.error else { return XCTFail() } guard let e2 = p2.error else { return XCTFail() } guard case PMKError.badInput = e1 else { return XCTFail() } guard case PMKError.badInput = e2 else { return XCTFail() } } func testStopsDequeueingOnceRejected() { let ex = expectation(description: "") enum Error: Swift.Error { case dummy } var x: UInt = 0 let generator = AnyIterator> { x += 1 switch x { case 0: fatalError() case 1: return Promise() case 2: return Promise(error: Error.dummy) case _: XCTFail() return nil } } when(fulfilled: generator, concurrently: 1).done { XCTFail("\($0)") }.catch { error in ex.fulfill() } waitForExpectations(timeout: 3) } func testWhenResolvedContinuesWhenRejected() { #if swift(>=5.3) let ex = expectation(description: "") enum Error: Swift.Error { case dummy } var x: UInt = 0 let generator = AnyIterator> { x += 1 switch x { case 0: fatalError() case 1: return Promise() case 2: return Promise(error: Error.dummy) case 3: return Promise() case _: return nil } } when(resolved: generator, concurrently: 1).done { results in XCTAssertEqual(results.count, 3) ex.fulfill() } waitForExpectations(timeout: 3) #endif } } ================================================ FILE: Tests/CorePromise/WhenResolvedTests.swift ================================================ // Created by Austin Feight on 3/19/16. // Copyright © 2016 Max Howell. All rights reserved. import PromiseKit import XCTest class JoinTests: XCTestCase { func testImmediates() { let successPromise = Promise() var joinFinished = false when(resolved: successPromise).done(on: nil) { _ in joinFinished = true } XCTAssert(joinFinished, "Join immediately finishes on fulfilled promise") let promise2 = Promise.value(2) let promise3 = Promise.value(3) let promise4 = Promise.value(4) var join2Finished = false when(resolved: promise2, promise3, promise4).done(on: nil) { _ in join2Finished = true } XCTAssert(join2Finished, "Join immediately finishes on fulfilled promises") } func testFulfilledAfterAllResolve() { let (promise1, seal1) = Promise.pending() let (promise2, seal2) = Promise.pending() let (promise3, seal3) = Promise.pending() var finished = false when(resolved: promise1, promise2, promise3).done(on: nil) { _ in finished = true } XCTAssertFalse(finished, "Not all promises have resolved") seal1.fulfill_() XCTAssertFalse(finished, "Not all promises have resolved") seal2.fulfill_() XCTAssertFalse(finished, "Not all promises have resolved") seal3.fulfill_() XCTAssert(finished, "All promises have resolved") } } ================================================ FILE: Tests/CorePromise/WhenTests.swift ================================================ import PromiseKit import Dispatch import XCTest class WhenTests: XCTestCase { func testEmpty() { let e1 = expectation(description: "") let promises: [Promise] = [] when(fulfilled: promises).done { _ in e1.fulfill() }.silenceWarning() let e2 = expectation(description: "") when(resolved: promises).done { _ in e2.fulfill() }.silenceWarning() wait(for: [e1, e2], timeout: 1) } func testInt() { let e1 = expectation(description: "") let p1 = Promise.value(1) let p2 = Promise.value(2) let p3 = Promise.value(3) let p4 = Promise.value(4) when(fulfilled: [p1, p2, p3, p4]).done { x in XCTAssertEqual(x[0], 1) XCTAssertEqual(x[1], 2) XCTAssertEqual(x[2], 3) XCTAssertEqual(x[3], 4) XCTAssertEqual(x.count, 4) e1.fulfill() }.silenceWarning() waitForExpectations(timeout: 1, handler: nil) } func testAnyInt() { #if swift(>=5.7) let e1 = expectation(description: "") let p1 = Promise.value(1) let g2 = Guarantee.value(2) let p3 = Promise.value(3) let g4 = Guarantee.value(4) when(fulfilled: [p1, g2, p3, g4]).done { x in XCTAssertEqual(x[0] as? Int, 1) XCTAssertEqual(x[1] as? Int, 2) XCTAssertEqual(x[2] as? Int, 3) XCTAssertEqual(x[3] as? Int, 4) XCTAssertEqual(x.count, 4) e1.fulfill() }.silenceWarning() waitForExpectations(timeout: 1, handler: nil) #endif } func testParameterPacks() { #if swift(>=5.9) let e1 = expectation(description: "") let p1 = Promise.value(1) let g2 = Guarantee.value("Hello") let p3 = Promise.value("world") let g4 = Guarantee.value(2) when(fulfilled: p1, g2, p3, g4).done { x1, x2, x3, x4 in XCTAssertEqual(x1, 1) XCTAssertEqual(x2, "Hello") XCTAssertEqual(x3, "world") XCTAssertEqual(x4, 2) e1.fulfill() }.silenceWarning() waitForExpectations(timeout: 1, handler: nil) #endif } func testDoubleTuple() { let e1 = expectation(description: "") let p1 = Promise.value(1) let p2 = Promise.value("abc") when(fulfilled: p1, p2).done{ x, y in XCTAssertEqual(x, 1) XCTAssertEqual(y, "abc") e1.fulfill() }.silenceWarning() waitForExpectations(timeout: 1, handler: nil) } func testTripleTuple() { let e1 = expectation(description: "") let p1 = Promise.value(1) let p2 = Promise.value("abc") let p3 = Promise.value( 1.0) when(fulfilled: p1, p2, p3).done { u, v, w in XCTAssertEqual(1, u) XCTAssertEqual("abc", v) XCTAssertEqual(1.0, w) e1.fulfill() }.silenceWarning() waitForExpectations(timeout: 1, handler: nil) } func testQuadrupleTuple() { let e1 = expectation(description: "") let p1 = Promise.value(1) let p2 = Promise.value("abc") let p3 = Promise.value(1.0) let p4 = Promise.value(true) when(fulfilled: p1, p2, p3, p4).done { u, v, w, x in XCTAssertEqual(1, u) XCTAssertEqual("abc", v) XCTAssertEqual(1.0, w) XCTAssertEqual(true, x) e1.fulfill() }.silenceWarning() waitForExpectations(timeout: 1, handler: nil) } func testQuintupleTuple() { let e1 = expectation(description: "") let p1 = Promise.value(1) let p2 = Promise.value("abc") let p3 = Promise.value(1.0) let p4 = Promise.value(true) let p5 = Promise.value("a" as Character) when(fulfilled: p1, p2, p3, p4, p5).done { u, v, w, x, y in XCTAssertEqual(1, u) XCTAssertEqual("abc", v) XCTAssertEqual(1.0, w) XCTAssertEqual(true, x) XCTAssertEqual("a" as Character, y) e1.fulfill() }.silenceWarning() waitForExpectations(timeout: 1, handler: nil) } func testVoid() { let e1 = expectation(description: "") let p1 = Promise.value(1).done { _ in } let p2 = Promise.value(2).done { _ in } let p3 = Promise.value(3).done { _ in } let p4 = Promise.value(4).done { _ in } when(fulfilled: p1, p2, p3, p4).done(e1.fulfill).silenceWarning() waitForExpectations(timeout: 1, handler: nil) } func testRejected() { enum Error: Swift.Error { case dummy } let e1 = expectation(description: "") let p1 = after(.milliseconds(100)).map{ true } let p2: Promise = after(.milliseconds(200)).map{ throw Error.dummy } let p3 = Promise.value(false) when(fulfilled: p1, p2, p3).catch { _ in e1.fulfill() } waitForExpectations(timeout: 1, handler: nil) } func testProgress() { let ex = expectation(description: "") XCTAssertNil(Progress.current()) let p1 = after(.milliseconds(10)) let p2 = after(.milliseconds(20)) let p3 = after(.milliseconds(30)) let p4 = after(.milliseconds(40)) let progress = Progress(totalUnitCount: 1) progress.becomeCurrent(withPendingUnitCount: 1) when(guarantees: p1, p2, p3, p4).done { _ in XCTAssertEqual(progress.completedUnitCount, 1) ex.fulfill() } progress.resignCurrent() waitForExpectations(timeout: 1, handler: nil) } func testProgressDoesNotExceed100Percent() { let ex1 = expectation(description: "") let ex2 = expectation(description: "") XCTAssertNil(Progress.current()) let p1 = after(.milliseconds(10)) let p2 = after(.milliseconds(20)).done { throw NSError(domain: "a", code: 1, userInfo: nil) } let p3 = after(.milliseconds(30)) let p4 = after(.milliseconds(40)) let progress = Progress(totalUnitCount: 1) progress.becomeCurrent(withPendingUnitCount: 1) let promise = when(fulfilled: p1, p2, p3, p4) progress.resignCurrent() promise.catch { _ in ex2.fulfill() } var x = 0 func finally() { x += 1 if x == 4 { XCTAssertLessThanOrEqual(1, progress.fractionCompleted) XCTAssertEqual(progress.completedUnitCount, 1) ex1.fulfill() } } let q = DispatchQueue.main p1.done(on: q, finally) p2.ensure(on: q, finally).silenceWarning() p3.done(on: q, finally) p4.done(on: q, finally) waitForExpectations(timeout: 1, handler: nil) } func testUnhandledErrorHandlerDoesNotFire() { enum Error: Swift.Error { case test } let ex = expectation(description: "") let p1 = Promise(error: Error.test) let p2 = after(.milliseconds(100)) when(fulfilled: p1, p2).done{ _ in XCTFail() }.catch { error in XCTAssertTrue(error as? Error == Error.test) ex.fulfill() } waitForExpectations(timeout: 1, handler: nil) } func testUnhandledErrorHandlerDoesNotFireForStragglers() { enum Error: Swift.Error { case test case straggler } let ex1 = expectation(description: "") let ex2 = expectation(description: "") let ex3 = expectation(description: "") let p1 = Promise(error: Error.test) let p2 = after(.milliseconds(100)).done { throw Error.straggler } let p3 = after(.milliseconds(200)).done { throw Error.straggler } let whenFulfilledP1P2P3: Promise<(Void, Void, Void)> = when(fulfilled: p1, p2, p3) whenFulfilledP1P2P3.catch { error -> Void in XCTAssertTrue(Error.test == error as? Error) ex1.fulfill() } p2.ensure { after(.milliseconds(100)).done(ex2.fulfill) }.silenceWarning() p3.ensure { after(.milliseconds(100)).done(ex3.fulfill) }.silenceWarning() waitForExpectations(timeout: 1, handler: nil) } func testAllSealedRejectedFirstOneRejects() { enum Error: Swift.Error { case test1 case test2 case test3 } let ex = expectation(description: "") let p1 = Promise(error: Error.test1) let p2 = Promise(error: Error.test2) let p3 = Promise(error: Error.test3) let whenFulfilledP1P2P3: Promise = when(fulfilled: p1, p2, p3) whenFulfilledP1P2P3.catch { error in XCTAssertTrue(error as? Error == Error.test1) ex.fulfill() } waitForExpectations(timeout: 1) } func testGuaranteesWhenVoidVarArgs() { let ex1 = expectation(description: "") var someNumber = 0 let g1 = Guarantee { resolver in someNumber += 1 resolver(()) } let g2 = Guarantee { resolver in someNumber += 2 resolver(()) } when(g1, g2).done { XCTAssertEqual(someNumber, 3) ex1.fulfill() } wait(for: [ex1], timeout: 10) } func testGuaranteesWhenVarArgs() { let ex1 = expectation(description: "") let g1 = Guarantee.value(1) let g2 = Guarantee.value(4) let g3 = Guarantee.value(2) let g4 = Guarantee.value(5) let g5 = Guarantee.value(3) when(g1, g2, g3, g4, g5).done { XCTAssertEqual($0, [1, 4, 2, 5, 3]) ex1.fulfill() } wait(for: [ex1], timeout: 10) } func testGuaranteesWhenVoidArray() { let ex1 = expectation(description: "") var someNumber = 0 when(guarantees: (0..<100).map { _ in Guarantee { resolver in someNumber += 1 resolver(()) } }).done { XCTAssertEqual(someNumber, 100) ex1.fulfill() } wait(for: [ex1], timeout: 10) } func testGuaranteesWhenArray() { let ex1 = expectation(description: "") when(guarantees: (0..<100).map { Guarantee.value($0) }).done { XCTAssertEqual($0, Array(0..<100)) ex1.fulfill() } wait(for: [ex1], timeout: 10) } func testDoubleTupleGuarantees() { let e1 = expectation(description: "") let g1 = Guarantee.value(1) let g2 = Guarantee.value("abc") when(guarantees: g1, g2).done { x, y in XCTAssertEqual(x, 1) XCTAssertEqual(y, "abc") e1.fulfill() } waitForExpectations(timeout: 1, handler: nil) } func testTripleTupleGuarantees() { let e1 = expectation(description: "") let g1 = Guarantee.value(1) let g2 = Guarantee.value("abc") let g3 = Guarantee.value( 1.0) when(guarantees: g1, g2, g3).done { u, v, w in XCTAssertEqual(1, u) XCTAssertEqual("abc", v) XCTAssertEqual(1.0, w) e1.fulfill() } waitForExpectations(timeout: 1, handler: nil) } func testQuadrupleTupleGuarantees() { let e1 = expectation(description: "") let g1 = Guarantee.value(1) let g2 = Guarantee.value("abc") let g3 = Guarantee.value(1.0) let g4 = Guarantee.value(true) when(guarantees: g1, g2, g3, g4).done { u, v, w, x in XCTAssertEqual(1, u) XCTAssertEqual("abc", v) XCTAssertEqual(1.0, w) XCTAssertEqual(true, x) e1.fulfill() } waitForExpectations(timeout: 1, handler: nil) } func testQuintupleTupleGuarantees() { let e1 = expectation(description: "") let g1 = Guarantee.value(1) let g2 = Guarantee.value("abc") let g3 = Guarantee.value(1.0) let g4 = Guarantee.value(true) let g5 = Guarantee.value("a" as Character) when(guarantees: g1, g2, g3, g4, g5).done { u, v, w, x, y in XCTAssertEqual(1, u) XCTAssertEqual("abc", v) XCTAssertEqual(1.0, w) XCTAssertEqual(true, x) XCTAssertEqual("a" as Character, y) e1.fulfill() } waitForExpectations(timeout: 1, handler: nil) } } ================================================ FILE: Tests/CorePromise/XCTestManifests.swift ================================================ #if !canImport(ObjectiveC) import XCTest extension AfterTests { // DO NOT MODIFY: This is autogenerated, use: // `swift test --generate-linuxmain` // to regenerate. static let __allTests__AfterTests = [ ("testNegative", testNegative), ("testPositive", testPositive), ("testZero", testZero), ] } extension AsyncTests { // DO NOT MODIFY: This is autogenerated, use: // `swift test --generate-linuxmain` // to regenerate. static let __allTests__AsyncTests = [ ("testAsyncGuaranteeValue", testAsyncGuaranteeValue), ("testAsyncGuaranteeValue", testAsyncGuaranteeValue), ("testAsyncPromiseCancel", testAsyncPromiseCancel), ("testAsyncPromiseCancel", testAsyncPromiseCancel), ("testAsyncPromiseThrow", testAsyncPromiseThrow), ("testAsyncPromiseThrow", testAsyncPromiseThrow), ("testAsyncPromiseValue", testAsyncPromiseValue), ("testAsyncPromiseValue", testAsyncPromiseValue), ] } extension CancellationTests { // DO NOT MODIFY: This is autogenerated, use: // `swift test --generate-linuxmain` // to regenerate. static let __allTests__CancellationTests = [ ("testBridgeToNSError", testBridgeToNSError), ("testCancellation", testCancellation), ("testDoesntCrashSwift", testDoesntCrashSwift), ("testFoundationBridging1", testFoundationBridging1), ("testFoundationBridging2", testFoundationBridging2), ("testIsCancelled", testIsCancelled), ("testRecoverWithCancellation", testRecoverWithCancellation), ("testThrowCancellableErrorThatIsNotCancelled", testThrowCancellableErrorThatIsNotCancelled), ] } extension CatchableTests { // DO NOT MODIFY: This is autogenerated, use: // `swift test --generate-linuxmain` // to regenerate. static let __allTests__CatchableTests = [ ("test__conditional_recover", test__conditional_recover), ("test__conditional_recover__fulfilled_path", test__conditional_recover__fulfilled_path), ("test__conditional_recover__ignores_cancellation_but_fed_cancellation", test__conditional_recover__ignores_cancellation_but_fed_cancellation), ("test__conditional_recover__no_recover", test__conditional_recover__no_recover), ("test__full_recover", test__full_recover), ("test__full_recover__fulfilled_path", test__full_recover__fulfilled_path), ("test__void_specialized_conditional_recover", test__void_specialized_conditional_recover), ("test__void_specialized_conditional_recover__fulfilled_path", test__void_specialized_conditional_recover__fulfilled_path), ("test__void_specialized_conditional_recover__ignores_cancellation_but_fed_cancellation", test__void_specialized_conditional_recover__ignores_cancellation_but_fed_cancellation), ("test__void_specialized_conditional_recover__no_recover", test__void_specialized_conditional_recover__no_recover), ("test__void_specialized_full_recover", test__void_specialized_full_recover), ("test__void_specialized_full_recover__fulfilled_path", test__void_specialized_full_recover__fulfilled_path), ("testCauterize", testCauterize), ("testEnsureThen_Error", testEnsureThen_Error), ("testEnsureThen_Value", testEnsureThen_Value), ("testFinally", testFinally), ] } extension CombineTests { // DO NOT MODIFY: This is autogenerated, use: // `swift test --generate-linuxmain` // to regenerate. static let __allTests__CombineTests = [ ("testCombineGuaranteeValue", testCombineGuaranteeValue), ("testCombinePromiseThrow", testCombinePromiseThrow), ("testCombinePromiseValue", testCombinePromiseValue), ("testGuaranteeCombineValue", testGuaranteeCombineValue), ("testPromiseCombineThrows", testPromiseCombineThrows), ("testPromiseCombineValue", testPromiseCombineValue), ] } extension GuaranteeTests { // DO NOT MODIFY: This is autogenerated, use: // `swift test --generate-linuxmain` // to regenerate. static let __allTests__GuaranteeTests = [ ("testCompactMapValues", testCompactMapValues), ("testCompactMapValuesByKeyPath", testCompactMapValuesByKeyPath), ("testFilterValues", testFilterValues), ("testFilterValuesByKeyPath", testFilterValuesByKeyPath), ("testFlatMapValues", testFlatMapValues), ("testInit", testInit), ("testMap", testMap), ("testMapByKeyPath", testMapByKeyPath), ("testMapValues", testMapValues), ("testMapValuesByKeyPath", testMapValuesByKeyPath), ("testNoAmbiguityForValue", testNoAmbiguityForValue), ("testSorted", testSorted), ("testSortedBy", testSortedBy), ("testThenFlatMap", testThenFlatMap), ("testThenMap", testThenMap), ("testWait", testWait), ] } extension HangTests { // DO NOT MODIFY: This is autogenerated, use: // `swift test --generate-linuxmain` // to regenerate. static let __allTests__HangTests = [ ("test", test), ("testError", testError), ] } extension JoinTests { // DO NOT MODIFY: This is autogenerated, use: // `swift test --generate-linuxmain` // to regenerate. static let __allTests__JoinTests = [ ("testFulfilledAfterAllResolve", testFulfilledAfterAllResolve), ("testImmediates", testImmediates), ] } extension LoggingTests { // DO NOT MODIFY: This is autogenerated, use: // `swift test --generate-linuxmain` // to regenerate. static let __allTests__LoggingTests = [ ("testCauterizeIsLogged", testCauterizeIsLogged), ("testGuaranteeWaitOnMainThreadLogged", testGuaranteeWaitOnMainThreadLogged), ("testLogging", testLogging), ("testPendingGuaranteeDeallocatedIsLogged", testPendingGuaranteeDeallocatedIsLogged), ("testPendingPromiseDeallocatedIsLogged", testPendingPromiseDeallocatedIsLogged), ("testPromiseWaitOnMainThreadLogged", testPromiseWaitOnMainThreadLogged), ] } extension PMKDefaultDispatchQueueTest { // DO NOT MODIFY: This is autogenerated, use: // `swift test --generate-linuxmain` // to regenerate. static let __allTests__PMKDefaultDispatchQueueTest = [ ("testOverrodeDefaultAlwaysQueue", testOverrodeDefaultAlwaysQueue), ("testOverrodeDefaultCatchQueue", testOverrodeDefaultCatchQueue), ("testOverrodeDefaultThenQueue", testOverrodeDefaultThenQueue), ] } extension PMKErrorTests { // DO NOT MODIFY: This is autogenerated, use: // `swift test --generate-linuxmain` // to regenerate. static let __allTests__PMKErrorTests = [ ("testCustomDebugStringConvertible", testCustomDebugStringConvertible), ("testCustomStringConvertible", testCustomStringConvertible), ] } extension PromiseTests { // DO NOT MODIFY: This is autogenerated, use: // `swift test --generate-linuxmain` // to regenerate. static let __allTests__PromiseTests = [ ("testCanMakeVoidPromise", testCanMakeVoidPromise), ("testCannotFulfillWithError", testCannotFulfillWithError), ("testCustomStringConvertible", testCustomStringConvertible), ("testDispatchQueueAsyncExtensionCanThrowInBody", testDispatchQueueAsyncExtensionCanThrowInBody), ("testDispatchQueueAsyncExtensionReturnsPromise", testDispatchQueueAsyncExtensionReturnsPromise), ("testIsFulfilled", testIsFulfilled), ("testIsPending", testIsPending), ("testIsRejected", testIsRejected), ("testIsResolved", testIsResolved), ("testNoAmbiguityForValue", testNoAmbiguityForValue), ("testPipeForResolved", testPipeForResolved), ("testThrowInFirstly", testThrowInFirstly), ("testThrowInInitializer", testThrowInInitializer), ("testWait", testWait), ] } extension RaceTests { // DO NOT MODIFY: This is autogenerated, use: // `swift test --generate-linuxmain` // to regenerate. static let __allTests__RaceTests = [ ("test1", test1), ("test1Array", test1Array), ("test2", test2), ("test2Array", test2Array), ("testEmptyArray", testEmptyArray), ("testFulfilled", testFulfilled), ("testFulfilledEmptyArray", testFulfilledEmptyArray), ("testFulfilledWithNoWinner", testFulfilledWithNoWinner), ] } extension RegressionTests { // DO NOT MODIFY: This is autogenerated, use: // `swift test --generate-linuxmain` // to regenerate. static let __allTests__RegressionTests = [ ("testReturningPreviousPromiseWorks", testReturningPreviousPromiseWorks), ] } extension StressTests { // DO NOT MODIFY: This is autogenerated, use: // `swift test --generate-linuxmain` // to regenerate. static let __allTests__StressTests = [ ("testThenDataRace", testThenDataRace), ("testThensAreSequentialForLongTime", testThensAreSequentialForLongTime), ("testZalgoDataRace", testZalgoDataRace), ] } extension ThenableTests { // DO NOT MODIFY: This is autogenerated, use: // `swift test --generate-linuxmain` // to regenerate. static let __allTests__ThenableTests = [ ("testBarrier", testBarrier), ("testCompactMap", testCompactMap), ("testCompactMapByKeyPath", testCompactMapByKeyPath), ("testCompactMapThrows", testCompactMapThrows), ("testCompactMapValues", testCompactMapValues), ("testCompactMapValuesByKeyPath", testCompactMapValuesByKeyPath), ("testDispatchFlagsSyntax", testDispatchFlagsSyntax), ("testFilterValues", testFilterValues), ("testFilterValuesByKeyPath", testFilterValuesByKeyPath), ("testFirstValueForEmpty", testFirstValueForEmpty), ("testGet", testGet), ("testLastValueForEmpty", testLastValueForEmpty), ("testMap", testMap), ("testMapByKeyPath", testMapByKeyPath), ("testMapValues", testMapValues), ("testMapValuesByKeyPath", testMapValuesByKeyPath), ("testPMKErrorCompactMap", testPMKErrorCompactMap), ("testRejectedPromiseCompactMap", testRejectedPromiseCompactMap), ("testThenFlatMap", testThenFlatMap), ("testThenMap", testThenMap), ("testThenOffRejected", testThenOffRejected), ] } extension WhenConcurrentTestCase_Swift { // DO NOT MODIFY: This is autogenerated, use: // `swift test --generate-linuxmain` // to regenerate. static let __allTests__WhenConcurrentTestCase_Swift = [ ("testStopsDequeueingOnceRejected", testStopsDequeueingOnceRejected), ("testWhen", testWhen), ("testWhenConcurrency", testWhenConcurrency), ("testWhenConcurrencyLessThanZero", testWhenConcurrencyLessThanZero), ("testWhenEmptyGenerator", testWhenEmptyGenerator), ("testWhenGeneratorError", testWhenGeneratorError), ("testWhenResolvedContinuesWhenRejected", testWhenResolvedContinuesWhenRejected), ] } extension WhenTests { // DO NOT MODIFY: This is autogenerated, use: // `swift test --generate-linuxmain` // to regenerate. static let __allTests__WhenTests = [ ("testAllSealedRejectedFirstOneRejects", testAllSealedRejectedFirstOneRejects), ("testAnyInt", testAnyInt), ("testDoubleTuple", testDoubleTuple), ("testDoubleTupleGuarantees", testDoubleTupleGuarantees), ("testEmpty", testEmpty), ("testGuaranteesWhenArray", testGuaranteesWhenArray), ("testGuaranteesWhenVarArgs", testGuaranteesWhenVarArgs), ("testGuaranteesWhenVoidArray", testGuaranteesWhenVoidArray), ("testGuaranteesWhenVoidVarArgs", testGuaranteesWhenVoidVarArgs), ("testInt", testInt), ("testProgress", testProgress), ("testProgressDoesNotExceed100Percent", testProgressDoesNotExceed100Percent), ("testQuadrupleTuple", testQuadrupleTuple), ("testQuadrupleTupleGuarantees", testQuadrupleTupleGuarantees), ("testQuintupleTuple", testQuintupleTuple), ("testQuintupleTupleGuarantees", testQuintupleTupleGuarantees), ("testRejected", testRejected), ("testTripleTuple", testTripleTuple), ("testTripleTupleGuarantees", testTripleTupleGuarantees), ("testUnhandledErrorHandlerDoesNotFire", testUnhandledErrorHandlerDoesNotFire), ("testUnhandledErrorHandlerDoesNotFireForStragglers", testUnhandledErrorHandlerDoesNotFireForStragglers), ("testVoid", testVoid), ] } extension WrapTests { // DO NOT MODIFY: This is autogenerated, use: // `swift test --generate-linuxmain` // to regenerate. static let __allTests__WrapTests = [ ("testError", testError), ("testInvalidCallingConvention", testInvalidCallingConvention), ("testInvertedCallingConvention", testInvertedCallingConvention), ("testIsFulfilled", testIsFulfilled), ("testNonOptionalFirstParameter", testNonOptionalFirstParameter), ("testPendingPromiseDeallocated", testPendingPromiseDeallocated), ("testSuccess", testSuccess), ("testSwiftResultError", testSwiftResultError), ("testSwiftResultSuccess", testSwiftResultSuccess), ("testVoidCompletionValue", testVoidCompletionValue), ("testVoidResolverFulfillAmbiguity", testVoidResolverFulfillAmbiguity), ] } extension ZalgoTests { // DO NOT MODIFY: This is autogenerated, use: // `swift test --generate-linuxmain` // to regenerate. static let __allTests__ZalgoTests = [ ("test1", test1), ("test2", test2), ("test3", test3), ("test4", test4), ] } public func __allTests() -> [XCTestCaseEntry] { return [ testCase(AfterTests.__allTests__AfterTests), testCase(AsyncTests.__allTests__AsyncTests), testCase(CancellationTests.__allTests__CancellationTests), testCase(CatchableTests.__allTests__CatchableTests), testCase(CombineTests.__allTests__CombineTests), testCase(GuaranteeTests.__allTests__GuaranteeTests), testCase(HangTests.__allTests__HangTests), testCase(JoinTests.__allTests__JoinTests), testCase(LoggingTests.__allTests__LoggingTests), testCase(PMKDefaultDispatchQueueTest.__allTests__PMKDefaultDispatchQueueTest), testCase(PMKErrorTests.__allTests__PMKErrorTests), testCase(PromiseTests.__allTests__PromiseTests), testCase(RaceTests.__allTests__RaceTests), testCase(RegressionTests.__allTests__RegressionTests), testCase(StressTests.__allTests__StressTests), testCase(ThenableTests.__allTests__ThenableTests), testCase(WhenConcurrentTestCase_Swift.__allTests__WhenConcurrentTestCase_Swift), testCase(WhenTests.__allTests__WhenTests), testCase(WrapTests.__allTests__WrapTests), testCase(ZalgoTests.__allTests__ZalgoTests), ] } #endif ================================================ FILE: Tests/CorePromise/ZalgoTests.swift ================================================ import XCTest import PromiseKit class ZalgoTests: XCTestCase { func test1() { var resolved = false Promise.value(1).done(on: nil) { _ in resolved = true }.silenceWarning() XCTAssertTrue(resolved) } func test2() { let p1 = Promise.value(1).map(on: nil) { x in return 2 } XCTAssertEqual(p1.value!, 2) var x = 0 let (p2, seal) = Promise.pending() p2.done(on: nil) { _ in x = 1 }.silenceWarning() XCTAssertEqual(x, 0) seal.fulfill(1) XCTAssertEqual(x, 1) } // returning a pending promise from its own zalgo’d then handler doesn’t hang func test3() { let ex = (expectation(description: ""), expectation(description: "")) var p1: Promise! p1 = after(.milliseconds(100)).then(on: nil) { _ -> Promise in ex.0.fulfill() return p1 } p1.catch { err in defer{ ex.1.fulfill() } guard case PMKError.returnedSelf = err else { return XCTFail() } } waitForExpectations(timeout: 1) } // return a sealed promise from its own zalgo’d then handler doesn’t hang func test4() { let ex = expectation(description: "") let p1 = Promise.value(1) p1.then(on: nil) { _ -> Promise in ex.fulfill() return p1 }.silenceWarning() waitForExpectations(timeout: 1) } } ================================================ FILE: Tests/DeprecationTests.swift ================================================ import PromiseKit import XCTest class DeprecationTests: XCTestCase { func testWrap1() { let dummy = 10 func completion(_ body: (_ a: Int?, _ b: Error?) -> Void) { body(dummy, nil) } let ex = expectation(description: "") wrap(completion).done { XCTAssertEqual($0, dummy) ex.fulfill() } wait(for: [ex], timeout: 10) } func testWrap2() { let dummy = 10 func completion(_ body: (_ a: Int, _ b: Error?) -> Void) { body(dummy, nil) } let ex = expectation(description: "") wrap(completion).done { XCTAssertEqual($0, dummy) ex.fulfill() } wait(for: [ex], timeout: 10) } func testWrap3() { let dummy = 10 func completion(_ body: (_ a: Error?, _ b: Int?) -> Void) { body(nil, dummy) } let ex = expectation(description: "") wrap(completion).done { XCTAssertEqual($0, dummy) ex.fulfill() } wait(for: [ex], timeout: 10) } func testWrap4() { let dummy = 10 func completion(_ body: (_ a: Error?) -> Void) { body(nil) } let ex = expectation(description: "") wrap(completion).done { ex.fulfill() } wait(for: [ex], timeout: 10) } func testWrap5() { let dummy = 10 func completion(_ body: (_ a: Int) -> Void) { body(dummy) } let ex = expectation(description: "") wrap(completion).done { XCTAssertEqual($0, dummy) ex.fulfill() } wait(for: [ex], timeout: 10) } func testAlways() { let ex = expectation(description: "") Promise.value(1).always(execute: ex.fulfill) wait(for: [ex], timeout: 10) } #if PMKFullDeprecations func testFlatMap() { let ex = expectation(description: "") Promise.value(1).flatMap { _ -> Int? in nil }.catch { //TODO should be `flatMap`, but how to enact that without causing // compiler to warn when building PromiseKit for end-users? LOL guard case PMKError.compactMap = $0 else { return XCTFail() } ex.fulfill() } wait(for: [ex], timeout: 10) } func testSequenceMap() { let ex = expectation(description: "") Promise.value([1, 2]).map { $0 + 1 }.done { XCTAssertEqual($0, [2, 3]) ex.fulfill() }.silenceWarning() wait(for: [ex], timeout: 10) } func testSequenceFlatMap() { let ex = expectation(description: "") Promise.value([1, 2]).flatMap { [$0 + 1, $0 + 2] }.done { XCTAssertEqual($0, [2, 3, 3, 4]) ex.fulfill() }.silenceWarning() wait(for: [ex], timeout: 10) } #endif func testSequenceFilter() { let ex = expectation(description: "") Promise.value([0, 1, 2, 3]).filter { $0 < 2 }.done { XCTAssertEqual($0, [0, 1]) ex.fulfill() }.silenceWarning() wait(for: [ex], timeout: 10) } func testSorted() { let ex = expectation(description: "") Promise.value([5, 2, 1, 8]).sorted().done { XCTAssertEqual($0, [1,2,5,8]) ex.fulfill() } wait(for: [ex], timeout: 10) } func testFirst() { XCTAssertEqual(Promise.value([1,2]).first.value, 1) } func testLast() { XCTAssertEqual(Promise.value([1,2]).last.value, 2) } func testPMKErrorFlatMap() { XCTAssertNotNil(PMKError.flatMap(1, Int.self).errorDescription) } } extension Promise { func silenceWarning() {} } ================================================ FILE: Tests/JS-A+/.gitignore ================================================ # From https://github.com/github/gitignore/blob/master/Node.gitignore # Logs logs *.log npm-debug.log* yarn-debug.log* yarn-error.log* # Runtime data pids *.pid *.seed *.pid.lock # Directory for instrumented libs generated by jscoverage/JSCover lib-cov # Coverage directory used by tools like istanbul coverage # nyc test coverage .nyc_output # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) .grunt # Bower dependency directory (https://bower.io/) bower_components # node-waf configuration .lock-wscript # Compiled binary addons (https://nodejs.org/api/addons.html) build/Release # Dependency directories node_modules/ jspm_packages/ # Typescript v1 declaration files typings/ # Optional npm cache directory .npm # Optional eslint cache .eslintcache # Optional REPL history .node_repl_history # Output of 'npm pack' *.tgz # Yarn Integrity file .yarn-integrity # dotenv environment variables file .env # next.js build output .next ================================================ FILE: Tests/JS-A+/AllTests.swift ================================================ // // AllTests.swift // PMKJSA+Tests // // Created by Lois Di Qual on 2/28/18. // #if swift(>=3.2) && !os(watchOS) import XCTest import PromiseKit import JavaScriptCore class AllTests: XCTestCase { func testAll() { let scriptPath = URL(fileURLWithPath: #file).deletingLastPathComponent().appendingPathComponent("build/build.js") guard FileManager.default.fileExists(atPath: scriptPath.path) else { return print("Skipping JS-A+: see README for instructions on how to build") } guard let script = try? String(contentsOf: scriptPath) else { return XCTFail("Couldn't read content of test suite JS file") } let context = JSUtils.sharedContext // Add a global exception handler context.exceptionHandler = { context, exception in guard let exception = exception else { return XCTFail("Unknown JS exception") } JSUtils.printStackTrace(exception: exception, includeExceptionDescription: true) } // Setup mock functions (timers, console.log, etc) let environment = MockNodeEnvironment() environment.setup(with: context) // Expose JSPromise in the javascript context context.setObject(JSPromise.self, forKeyedSubscript: "JSPromise" as NSString) // Create adapter guard let adapter = JSValue(object: NSDictionary(), in: context) else { fatalError("Couldn't create adapter") } adapter.setObject(JSAdapter.resolved, forKeyedSubscript: "resolved" as NSString) adapter.setObject(JSAdapter.rejected, forKeyedSubscript: "rejected" as NSString) adapter.setObject(JSAdapter.deferred, forKeyedSubscript: "deferred" as NSString) // Evaluate contents of `build.js`, which exposes `runTests` in the global context context.evaluateScript(script) guard let runTests = context.objectForKeyedSubscript("runTests") else { return XCTFail("Couldn't find `runTests` in JS context") } // Create a callback that's called whenever there's a failure let onFail: @convention(block) (JSValue, JSValue) -> Void = { test, error in guard let test = test.toString(), let error = error.toString() else { return XCTFail("Unknown test failure") } XCTFail("\(test) failed: \(error)") } let onFailValue: JSValue = JSValue(object: onFail, in: context) // Create a new callback that we'll send to `runTest` so that it notifies when tests are done running. let expectation = self.expectation(description: "async") let onDone: @convention(block) (JSValue) -> Void = { failures in expectation.fulfill() } let onDoneValue: JSValue = JSValue(object: onDone, in: context) // If there's a need to only run one specific test, uncomment the next line and comment the one after // let testName: JSValue = JSValue(object: "2.3.1", in: context) let testName = JSUtils.undefined // Call `runTests` runTests.call(withArguments: [adapter, onFailValue, onDoneValue, testName]) self.wait(for: [expectation], timeout: 60) } } #endif ================================================ FILE: Tests/JS-A+/JSAdapter.swift ================================================ // // JSAdapter.swift // PMKJSA+Tests // // Created by Lois Di Qual on 3/2/18. // #if !os(watchOS) import Foundation import JavaScriptCore import PromiseKit enum JSAdapter { static let resolved: @convention(block) (JSValue) -> JSPromise = { value in return JSPromise(promise: .value(value)) } static let rejected: @convention(block) (JSValue) -> JSPromise = { reason in let error = JSUtils.JSError(reason: reason) let promise = Promise(error: error) return JSPromise(promise: promise) } static let deferred: @convention(block) () -> JSValue = { let context = JSContext.current() guard let object = JSValue(object: NSDictionary(), in: context) else { fatalError("Couldn't create object") } let pendingPromise = Promise.pending() let jsPromise = JSPromise(promise: pendingPromise.promise) // promise object.setObject(jsPromise, forKeyedSubscript: "promise" as NSString) // resolve let resolve: @convention(block) (JSValue) -> Void = { value in pendingPromise.resolver.fulfill(value) } object.setObject(resolve, forKeyedSubscript: "resolve" as NSString) // reject let reject: @convention(block) (JSValue) -> Void = { reason in let error = JSUtils.JSError(reason: reason) pendingPromise.resolver.reject(error) } object.setObject(reject, forKeyedSubscript: "reject" as NSString) return object } } #endif ================================================ FILE: Tests/JS-A+/JSPromise.swift ================================================ // // JSPromise.swift // PMKJSA+Tests // // Created by Lois Di Qual on 3/1/18. // #if !os(watchOS) import Foundation import XCTest import PromiseKit import JavaScriptCore @objc protocol JSPromiseProtocol: JSExport { func then(_: JSValue, _: JSValue) -> JSPromise } class JSPromise: NSObject, JSPromiseProtocol { let promise: Promise init(promise: Promise) { self.promise = promise } func then(_ onFulfilled: JSValue, _ onRejected: JSValue) -> JSPromise { // Keep a reference to the returned promise so we can comply to 2.3.1 var returnedPromiseRef: Promise? let afterFulfill = promise.then { value -> Promise in // 2.2.1: ignored if not a function guard JSUtils.isFunction(value: onFulfilled) else { return .value(value) } // Call `onFulfilled` // 2.2.5: onFulfilled/onRejected must be called as functions (with no `this` value) guard let returnValue = try JSUtils.call(function: onFulfilled, arguments: [JSUtils.undefined, value]) else { return .value(value) } // Extract JSPromise.promise if available, or use plain return value if let jsPromise = returnValue.toObjectOf(JSPromise.self) as? JSPromise { // 2.3.1: if returned value is the promise that `then` returned, throw TypeError if jsPromise.promise === returnedPromiseRef { throw JSUtils.JSError(reason: JSUtils.typeError(message: "Returned self")) } return jsPromise.promise } else { return .value(returnValue) } } let afterReject = promise.recover { error -> Promise in // 2.2.1: ignored if not a function guard let jsError = error as? JSUtils.JSError, JSUtils.isFunction(value: onRejected) else { throw error } // Call `onRejected` // 2.2.5: onFulfilled/onRejected must be called as functions (with no `this` value) guard let returnValue = try JSUtils.call(function: onRejected, arguments: [JSUtils.undefined, jsError.reason]) else { throw error } // Extract JSPromise.promise if available, or use plain return value if let jsPromise = returnValue.toObjectOf(JSPromise.self) as? JSPromise { // 2.3.1: if returned value is the promise that `then` returned, throw TypeError if jsPromise.promise === returnedPromiseRef { throw JSUtils.JSError(reason: JSUtils.typeError(message: "Returned self")) } return jsPromise.promise } else { return .value(returnValue) } } let newPromise = Promise> { resolver in _ = promise.tap(resolver.fulfill) }.then(on: nil) { result -> Promise in switch result { case .fulfilled: return afterFulfill case .rejected: return afterReject } } returnedPromiseRef = newPromise return JSPromise(promise: newPromise) } } #endif ================================================ FILE: Tests/JS-A+/JSUtils.swift ================================================ // // JSUtils.swift // PMKJSA+Tests // // Created by Lois Di Qual on 3/2/18. // #if !os(watchOS) import Foundation import JavaScriptCore enum JSUtils { class JSError: Error { let reason: JSValue init(reason: JSValue) { self.reason = reason } } static let sharedContext: JSContext = { guard let context = JSContext() else { fatalError("Couldn't create JS context") } return context }() static var undefined: JSValue { guard let undefined = JSValue(undefinedIn: JSUtils.sharedContext) else { fatalError("Couldn't create `undefined` value") } return undefined } static func typeError(message: String) -> JSValue { let message = message.replacingOccurrences(of: "\"", with: "\\\"") let script = "new TypeError(\"\(message)\")" guard let result = sharedContext.evaluateScript(script) else { fatalError("Couldn't create TypeError") } return result } // @warning: relies on lodash to be present static func isFunction(value: JSValue) -> Bool { guard let context = value.context else { return false } guard let lodash = context.objectForKeyedSubscript("_") else { fatalError("Couldn't get lodash in JS context") } guard let result = lodash.invokeMethod("isFunction", withArguments: [value]) else { fatalError("Couldn't invoke _.isFunction") } return result.toBool() } // Calls a JS function using `Function.prototype.call` and throws any potential exception wrapped in a JSError static func call(function: JSValue, arguments: [JSValue]) throws -> JSValue? { let context = JSUtils.sharedContext // Create a new exception handler that will store a potential exception // thrown in the handler. Save the value of the old handler. var caughtException: JSValue? let savedExceptionHandler = context.exceptionHandler context.exceptionHandler = { context, exception in caughtException = exception } // Call the handler let returnValue = function.invokeMethod("call", withArguments: arguments) context.exceptionHandler = savedExceptionHandler // If an exception was caught, throw it if let exception = caughtException { throw JSError(reason: exception) } return returnValue } static func printCurrentStackTrace() { guard let exception = JSUtils.sharedContext.evaluateScript("new Error()") else { return print("Couldn't get current stack trace") } printStackTrace(exception: exception, includeExceptionDescription: false) } static func printStackTrace(exception: JSValue, includeExceptionDescription: Bool) { guard let lineNumber = exception.objectForKeyedSubscript("line"), let column = exception.objectForKeyedSubscript("column"), let message = exception.objectForKeyedSubscript("message"), let stacktrace = exception.objectForKeyedSubscript("stack")?.toString() else { return print("Couldn't print stack trace") } if includeExceptionDescription { print("JS Exception at \(lineNumber):\(column): \(message)") } let lines = stacktrace.split(separator: "\n").map { "\t> \($0)" }.joined(separator: "\n") print(lines) } } #if !swift(>=3.2) extension String { func split(separator: Character, omittingEmptySubsequences: Bool = true) -> [String] { return characters.split(separator: separator, omittingEmptySubsequences: omittingEmptySubsequences).map(String.init) } var first: Character? { return characters.first } } #endif #endif ================================================ FILE: Tests/JS-A+/MockNodeEnvironment.swift ================================================ // // MockNodeEnvironment.swift // PMKJSA+Tests // // Created by Lois Di Qual on 3/1/18. // #if swift(>=3.2) && !os(watchOS) import Foundation import JavaScriptCore class MockNodeEnvironment { private var timers: [UInt32: Timer] = [:] func setup(with context: JSContext) { // console.log / console.error setupConsole(context: context) // setTimeout let setTimeout: @convention(block) (JSValue, Double) -> UInt32 = { function, intervalMs in let timerID = self.addTimer(interval: intervalMs / 1000, repeats: false, function: function) return timerID } context.setObject(setTimeout, forKeyedSubscript: "setTimeout" as NSString) // clearTimeout let clearTimeout: @convention(block) (JSValue) -> Void = { timeoutID in guard timeoutID.isNumber else { return } self.removeTimer(timerID: timeoutID.toUInt32()) } context.setObject(clearTimeout, forKeyedSubscript: "clearTimeout" as NSString) // setInterval let setInterval: @convention(block) (JSValue, Double) -> UInt32 = { function, intervalMs in let timerID = self.addTimer(interval: intervalMs / 1000, repeats: true, function: function) return timerID } context.setObject(setInterval, forKeyedSubscript: "setInterval" as NSString) // clearInterval let clearInterval: @convention(block) (JSValue) -> Void = { intervalID in guard intervalID.isNumber else { return } self.removeTimer(timerID: intervalID.toUInt32()) } context.setObject(clearInterval, forKeyedSubscript: "clearInterval" as NSString) } private func setupConsole(context: JSContext) { guard let console = context.objectForKeyedSubscript("console") else { fatalError("Couldn't get global `console` object") } let consoleLog: @convention(block) () -> Void = { guard let arguments = JSContext.currentArguments(), let format = arguments.first as? JSValue else { return } let otherArguments = arguments.dropFirst() if otherArguments.count == 0 { print(format) } else { let otherArguments = otherArguments.compactMap { $0 as? JSValue } let format = format.toString().replacingOccurrences(of: "%s", with: "%@") let expectedTypes = format.split(separator: "%", omittingEmptySubsequences: false).dropFirst().compactMap { $0.first }.map { String($0) } let typedArguments = otherArguments.enumerated().compactMap { index, value -> CVarArg? in let expectedType = expectedTypes[index] let converted: CVarArg switch expectedType { case "s": converted = value.toString() case "d": converted = value.toInt32() case "f": converted = value.toDouble() default: converted = value.toString() } return converted } let output = String(format: format, arguments: typedArguments) print(output) } } console.setObject(consoleLog, forKeyedSubscript: "log" as NSString) console.setObject(consoleLog, forKeyedSubscript: "error" as NSString) } private func addTimer(interval: TimeInterval, repeats: Bool, function: JSValue) -> UInt32 { let block = BlockOperation { DispatchQueue.main.async { function.call(withArguments: []) } } let timer = Timer.scheduledTimer(timeInterval: interval, target: block, selector: #selector(Operation.main), userInfo: nil, repeats: repeats) let rawHash = UUID().uuidString.hashValue #if swift(>=4.0) let hash = UInt32(truncatingIfNeeded: rawHash) #else let hash = UInt32(truncatingBitPattern: rawHash) #endif timers[hash] = timer return hash } private func removeTimer(timerID: UInt32) { guard let timer = timers[timerID] else { return print("Couldn't find timer \(timerID)") } timer.invalidate() timers[timerID] = nil } } #if swift(>=4.0) && !swift(>=4.1) || !swift(>=3.3) extension Sequence { func compactMap(_ transform: (Self.Element) throws -> T?) rethrows -> [T] { return try flatMap(transform) } } #endif #endif ================================================ FILE: Tests/JS-A+/README.md ================================================ Promises/A+ Compliance Test Suite (JavaScript) ============================================== What is this? ------------- This contains the necessary Swift and JS files to run the Promises/A+ compliance test suite from PromiseKit's unit tests. - Promise/A+ Spec: - Compliance Test Suite: Run tests --------- ``` $ npm install $ npm run build ``` then open `PromiseKit.xcodeproj` and run the `PMKJSA+Tests` unit test scheme. Known limitations ----------------- See `ignoredTests` in `index.js`. - 2.3.3 is disabled: Otherwise, if x is an object or function. This spec is a NOOP for Swift: - We have decided not to interact with other Promises A+ implementations - functions cannot have properties Upgrade the test suite ---------------------- ``` $ npm install --save promises-aplus-tests@latest $ npm run build ``` Develop ------- JavaScriptCore is a bit tedious to work with so here are a couple tips in case you're trying to debug the test suite. If you're editing JS files, enable live rebuilds: ``` $ npm run watch ``` If you're editing Swift files, a couple things you can do: - You can adjust `testName` in `AllTests.swift` to only run one test suite - You can call `JSUtils.printCurrentStackTrace()` at any time. It won't contain line numbers but some of the frame names might help. How it works ------------ The Promises/A+ test suite is written in JavaScript but PromiseKit is written in Swift/ObjC. For the test suite to run against swift code, we expose a promise wrapper `JSPromise` inside a JavaScriptCore context. This is done in a regular XCTestCase. Since JavaScriptCore doesn't support CommonJS imports, we inline all the JavaScript code into `build/build.js` using webpack. This includes all the npm dependencies (`promises-aplus-tests`, `mocha`, `sinon`, etc) as well as the glue code in `index.js`. `build.js` exposes one global variable `runTests(adapter, onFail, onDone, [testName])`. In our XCTestCase, a shared JavaScriptCore context is created, `build.js` is evaluated and now `runTests` is accessible from the Swift context. In our swift test, we create a JS-bridged `JSPromise` which only has one method `then(onFulfilled, onRejected) -> Promise`. It wraps a swift `Promise` and delegates call `then` calls to it. An [adapter](https://github.com/promises-aplus/promises-tests#adapters) – plain JS object which provides `revoled(value), rejected(reason), and deferred()` – is passed to `runTests` to run the whole JavaScript test suite. Errors and end events are reported back to Swift and piped to `XCTFail()` if necessary. Since JavaScriptCore isn't a node/web environment, there is quite a bit of stubbing necessary for all this to work: - The `fs` module is stubbed with an empty function - `console.log` redirects to `Swift.print` and provides only basic format parsing - `setTimeout/setInterval` are implemented with `Swift.Timer` behind the scenes and stored in a `[TimerID: Timer]` map. ================================================ FILE: Tests/JS-A+/index.js ================================================ const _ = require('lodash') require('mocha') // Ignored by design const ignoredTests = [ '2.3.3' ] module.exports = function(adapter, onFail, onDone, testName) { global.adapter = adapter const mocha = new Mocha({ ui: 'bdd' }) // Require all tests console.log('Loading test files') const requireTest = require.context('promises-aplus-tests/lib/tests', false, /\.js$/) requireTest.keys().forEach(file => { let currentTestName = _.replace(_.replace(file, './', ''), '.js', '') if (testName && currentTestName !== testName) { return } if (_.includes(ignoredTests, currentTestName)) { return } console.log(`\t${currentTestName}`) mocha.suite.emit('pre-require', global, file, mocha) mocha.suite.emit('require', requireTest(file), file, mocha) mocha.suite.emit('post-require', global, file, mocha) }) const runner = mocha.run(failures => { onDone(failures) }) runner.on('fail', (test, err) => { console.error(err) onFail(test.title, err) }) } ================================================ FILE: Tests/JS-A+/package.json ================================================ { "scripts": { "build": "webpack-cli", "watch": "webpack-cli --watch --mode development" }, "dependencies": { "babel-core": "^6.26.0", "babel-loader": "^7.1.3", "babel-preset-env": "^1.6.1", "lodash": "^4.17.21", "mocha": "^5.0.1", "promises-aplus-tests": "^2.1.2", "sinon": "^4.4.2", "webpack": "^4.0.1", "webpack-cli": "^2.0.9" } } ================================================ FILE: Tests/JS-A+/webpack.config.js ================================================ var webpack = require('webpack'); module.exports = { mode: 'development', context: __dirname, entry: './index.js', output: { path: __dirname + '/build', filename: 'build.js', library: 'runTests' }, stats: { warnings: false }, module: { rules: [ { test: /\.js$/, exclude: /(node_modules)/, use: { loader: 'babel-loader', options: { presets: ['env'] } } } ] }, node: { fs: 'empty' }, }; ================================================ FILE: Tests/LinuxMain.swift ================================================ import XCTest import APlus import CorePromise var tests = [XCTestCaseEntry]() tests += APlus.__allTests() tests += CorePromise.__allTests() XCTMain(tests) ================================================ FILE: tea.yaml ================================================ # https://tea.xyz/what-is-this-file # created with https://mash.pkgx.sh/mxcl/tea-register --- version: 1.0.0 codeOwners: - '0x5E2DE4A68df811AAAD32d71fb065e6946fA5C8d9' # mxcl quorum: 1