Convert Figma logo to code with AI

mxcl logoPromiseKit

Promises for Swift & ObjC.

14,226
1,456
14,226
18

Top Related Projects

20,444

:bird: :zap: Bluebird is a full featured promise library with unmatched performance.

14,940

A promise library for JavaScript

2,577

Bare bones Promises/A+ implementation

3,613

A lightweight library that provides tools for organizing asynchronous code

28,153

Async utilities for node and the browser

Quick Overview

PromiseKit is a popular Swift library that provides a powerful and expressive way to handle asynchronous programming. It simplifies complex asynchronous operations by using promises, making code more readable and easier to maintain compared to traditional callback-based approaches.

Pros

  • Improves code readability and reduces callback hell
  • Provides a robust error handling mechanism
  • Offers a wide range of extensions for common iOS frameworks
  • Supports both Swift and Objective-C

Cons

  • Learning curve for developers new to promises
  • May introduce overhead for simple asynchronous tasks
  • Can lead to overuse of promises in scenarios where simpler solutions suffice
  • Requires careful management to avoid retain cycles

Code Examples

  1. Basic Promise Usage:
firstly {
    fetchUser(id: 123)
}.then { user in
    fetchAvatar(for: user)
}.done { avatar in
    self.imageView.image = avatar
}.catch { error in
    print("An error occurred: \(error)")
}

This example demonstrates fetching a user and their avatar asynchronously using promises.

  1. Chaining Multiple Promises:
firstly {
    fetchData()
}.then { data in
    processData(data)
}.then { result in
    saveResult(result)
}.done { finalResult in
    print("Operation completed: \(finalResult)")
}.catch { error in
    print("Error: \(error)")
}

This example shows how to chain multiple asynchronous operations using promises.

  1. Parallel Promises:
let (users, posts) = try await when(fulfilled: fetchUsers(), fetchPosts())
print("Fetched \(users.count) users and \(posts.count) posts")

This example demonstrates how to execute multiple promises in parallel and wait for all of them to complete.

Getting Started

To use PromiseKit in your Swift project:

  1. Add PromiseKit to your project using Swift Package Manager, CocoaPods, or Carthage.
  2. Import the library in your Swift file:
import PromiseKit
  1. Start using promises in your asynchronous code:
func fetchData() -> Promise<Data> {
    return Promise { seal in
        URLSession.shared.dataTask(with: url) { data, _, error in
            if let error = error {
                seal.reject(error)
            } else if let data = data {
                seal.fulfill(data)
            }
        }.resume()
    }
}

This example shows how to wrap a traditional completion handler-based API with a promise.

Competitor Comparisons

20,444

:bird: :zap: Bluebird is a full featured promise library with unmatched performance.

Pros of Bluebird

  • Higher performance and faster execution compared to PromiseKit
  • More extensive feature set, including advanced utilities like Promise.map and Promise.reduce
  • Better cross-platform support, especially for older browsers and Node.js versions

Cons of Bluebird

  • Larger library size, which may impact load times in browser environments
  • Steeper learning curve due to its extensive API and advanced features
  • Less native integration with Swift and iOS development compared to PromiseKit

Code Comparison

PromiseKit:

firstly {
    fetchUser()
}.then { user in
    fetchAvatar(user)
}.done { avatar in
    self.imageView.image = avatar
}.catch { error in
    print("Error: \(error)")
}

Bluebird:

Promise.resolve()
  .then(fetchUser)
  .then(fetchAvatar)
  .then(avatar => {
    imageView.src = avatar;
  })
  .catch(error => {
    console.error("Error:", error);
  });

Both libraries provide similar syntax for chaining promises, but PromiseKit's syntax is more Swift-oriented, while Bluebird follows a more traditional JavaScript promise pattern. PromiseKit uses firstly and done for better readability, while Bluebird relies on standard promise methods like then and catch.

14,940

A promise library for JavaScript

Pros of Q

  • More mature and widely adopted in the JavaScript ecosystem
  • Supports a broader range of platforms, including older browsers
  • Offers more advanced features like progress tracking and cancellation

Cons of Q

  • Larger file size, which may impact performance in some applications
  • Less actively maintained compared to PromiseKit
  • Steeper learning curve for beginners due to its extensive API

Code Comparison

Q:

Q.fcall(function () {
    return 10;
})
.then(function (result) {
    console.log(result);
});

PromiseKit:

firstly {
    return 10
}.then { result in
    print(result)
}

Both libraries provide similar functionality for creating and chaining promises. Q uses a more JavaScript-centric approach, while PromiseKit is tailored for Swift and iOS development. PromiseKit's syntax is generally more concise and Swift-like, making it easier for iOS developers to integrate into their projects.

PromiseKit is actively maintained and optimized for iOS development, offering better integration with Apple's frameworks. It also provides a more lightweight solution, which can be beneficial for mobile applications where performance is crucial.

Q, on the other hand, offers a more comprehensive set of features and is better suited for complex asynchronous operations in JavaScript environments. Its wider adoption in the JavaScript community means more resources and third-party integrations are available.

2,577

Bare bones Promises/A+ implementation

Pros of Promise

  • Lightweight and minimalistic implementation
  • Focuses solely on Promise functionality without extra features
  • Easy to integrate into existing projects due to its simplicity

Cons of Promise

  • Less comprehensive feature set compared to PromiseKit
  • Fewer utility functions and extensions
  • May require additional libraries for more advanced use cases

Code Comparison

PromiseKit:

firstly {
    fetchUser()
}.then { user in
    fetchAvatar(user)
}.done { avatar in
    self.imageView.image = avatar
}.catch { error in
    self.show(error)
}

Promise:

fetchUser()
  .then(user => fetchAvatar(user))
  .then(avatar => {
    this.imageView.image = avatar;
  })
  .catch(error => {
    this.show(error);
  });

Summary

PromiseKit offers a more comprehensive solution with additional features and utilities, making it suitable for larger projects with complex asynchronous operations. Promise, on the other hand, provides a simpler and more lightweight implementation, focusing on core Promise functionality. PromiseKit's syntax is more Swift-oriented, while Promise follows a more traditional JavaScript-style approach. The choice between the two depends on the specific project requirements, language preferences, and the desired level of abstraction and feature set.

3,613

A lightweight library that provides tools for organizing asynchronous code

Pros of RSVP.js

  • Lightweight and focused solely on Promises, making it more suitable for projects that don't require a full-featured library
  • Better compatibility with older browsers, including IE8+
  • More active development and frequent updates

Cons of RSVP.js

  • Less extensive feature set compared to PromiseKit's comprehensive offerings
  • Lacks some of the convenience methods and extensions provided by PromiseKit
  • May require additional libraries or plugins for more advanced use cases

Code Comparison

RSVP.js:

RSVP.Promise.resolve(1)
  .then(value => value + 1)
  .then(value => console.log(value));

PromiseKit:

firstly {
    Promise.value(1)
}.map {
    $0 + 1
}.done {
    print($0)
}

Both libraries provide similar basic Promise functionality, but PromiseKit offers a more expressive and Swift-oriented syntax. RSVP.js follows a more traditional JavaScript Promise pattern, while PromiseKit leverages Swift's language features for a more idiomatic approach.

RSVP.js is better suited for JavaScript projects requiring broad browser support and a lightweight Promise implementation. PromiseKit, on the other hand, excels in Swift and Objective-C environments, offering a richer set of features and tighter integration with Apple's ecosystems.

28,153

Async utilities for node and the browser

Pros of async

  • More mature and widely adopted in the Node.js ecosystem
  • Supports a broader range of flow control patterns (e.g., parallel, series, waterfall)
  • Lightweight and focused on asynchronous operations

Cons of async

  • Limited to JavaScript/Node.js environments
  • Callback-based approach can lead to callback hell in complex scenarios
  • Lacks some modern features like cancellation and progress tracking

Code Comparison

async:

async.waterfall([
    function(callback) {
        callback(null, 'one', 'two');
    },
    function(arg1, arg2, callback) {
        callback(null, 'three');
    }
], function (err, result) {
    console.log(result);
});

PromiseKit:

firstly {
    fetch(url)
}.then { data in
    parse(data)
}.done { result in
    print(result)
}.catch { error in
    print(error)
}

Summary

async is a popular choice for Node.js developers, offering a wide range of flow control patterns and a lightweight approach to handling asynchronous operations. However, it's limited to JavaScript environments and can lead to callback hell in complex scenarios.

PromiseKit, on the other hand, provides a more modern promise-based approach with support for multiple languages and advanced features like cancellation. It offers a cleaner syntax for handling asynchronous operations but may have a steeper learning curve for developers new to promises.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

PromiseKit

badge-pod badge-languages badge-pms badge-platforms codecov


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.

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

Quick Start

In your Podfile:

use_frameworks!

target "Change Me!" do
  pod "PromiseKit", "~> 8"
end

PromiseKit 8 supports recent Xcodes (13+). Some Podspecs were dropped as a result. 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).

For Carthage, SwiftPM, Accio, etc., or for instructions when using older Swifts or Xcodes, see our Installation Guide. We recommend Carthage or 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. See Async+ 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.

Documentation

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.:

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:

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:

// 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, 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