Git Product home page Git Product logo

promises's Introduction

promises's People

Contributors

basthomas avatar bc-lee avatar benchr267 avatar benemdon avatar chuckhays avatar codeeagle avatar cspickert avatar dmace2 avatar edudnyk avatar ellishg avatar eric avatar ethanlozano avatar faimin avatar fitsyu avatar gabrielvieira avatar grigorye avatar hashier avatar iainsmith avatar jeff-h avatar jonathanekim avatar kimdv avatar krausefx avatar krzysztofmoch avatar leilee avatar ncooke3 avatar nzhuk avatar shoumikhin avatar status302 avatar sushichop avatar ykjchen avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

promises's Issues

Pending promise with pecific queue

It's possible to do something like this ?:

let promise = Promise<Void>.pending(queue: queue)

or

let promise = Promise<Void>.init(queue: queue)

after that resolve if manually

if success {
  promise.fulfill(())
} else {
  promise.reject(error)
}

Map extension

There is any intention to provide a Map extension?

Discussion: Conversion of NSException to NSError

There are several places where FBLPromise uses Objective-C exception handling to catch NSExceptions and convert them to NSErrors. I see several problems in this approach:

  1. Exceptions in Objective-C are usually used for fatal errors or programmer errors. Recovering from most exceptions results in undefined state.
  2. By default Objective-C is not exception-safe when using ARC. This leads to leaked memory. There is a flag to opt in to making ARC exception-safe (-fobjc-arc-exceptions) but this has to be used for all code participating in the stack where an exception is thrown which in most cases can't be guaranteed.

What was the reasoning behind recovering from exceptions?

Promise fulfil/reject have broken architecture

Promise class should not have fulfil() and reject() methods — instead, they must be moved to separate class like PromiseSource.

Because currently it is a leak in incapsulation: methods of class that return promises for underlying scheduled operations should not allow fulfillment and rejection of these operations by external user.

How do I cancel a promise?

A use case is autocomplete. When user types, I send out a request to query the completion info but if the user types fast enough, I want to cancel previous sent request before sending the new one.

Thanks

Benchmark compare to Tomorrowland

Could you add Tomorrowland to the benchmarks? I'm curious how it stacks up, since Tomorrowland uses atomics internally instead of locks/queues.

I'd also love to see your benchmark methodology. I see benchmarks for Promises in the repo, but no information on how you collected numbers for the other frameworks.

all(), when() with different Promise<Value>

How can I use something like this:

let void = Promise<Void>.pending()
let int = Promise<Int>.pending()

when(void, int).then({ (res) in
    print(res)
})

void.fulfill(())
int.fulfill(1)

I get this: screen shot 2018-02-14 at 10 47 04

Can we implement something like this example

When using Promises in real world apps this feature is very useful.
I understand that this will break current API

FBLPromise with Bool as Value in ObjC

Hi all,

Silly question, how do I create a Promise that produces streams of Bool values in Objective-C. Since, BOOL is not a pointer type in ObjC, should I use NSNumber instead?

Many thanks.
Chalk

Question: Exposing state variables for Promise

Sorry for leaving this as an Issue when it's more a "Request for change"

I notice that there are three protected accessors on Promises called isPending, isFulfilled, and isRejected. I've run into a case where it would be very useful to be able to introspect the isPending value in a synchronous way, but can't. Is there a reason for these variables to be protected, rather than being read-only public?

For the record, my use case is that I have a cache access function that returns a Promise, meaning that it's likely that it has either already been fulfilled or it will take quite some time to fulfill. I would like to be able to introspect that value synchronously so that I can show a loading spinner before attaching the handler via the .then chain. The app currently just always shows the loading spinner, but it is an unpleasant experience to flash it very quickly and it strikes me that there would be no issue with exposing this value.

Please let me know if there's something I'm missing here, thanks!

Question: Correct use of "Broken Chains"

Hi,
I've recently stumbled upon a specific use-case and decided to clarify on the correct use of the Promises. The use-case is the need to execute some code on the promise fulfillment and just propagate the error further if the promise has been rejected.

The example
I'd like to authenticate the user with the OAuth2 Password Grant, but keep the implementation details, such as the specific of the Token storage out of the ViewController.

So, let's consider, we have a LoginService:

class LoginService {
  lazy var auth = AuthService()
  lazy var client = RESTClient(accessToken: auth.token)

  func login(username: String = "", password: String = "") -> Promise<String> {
    weak var weakSelf = self
    return client.request(API.authenticate(username: username, password: password)).then({ (token) -> Promise<String> in
      let auth = weakSelf?.auth
      auth?.token = token
      return Promise<String>(token)
    })
  }

  @discardableResult func logOut() -> Promise<Void> {
    auth.eraseAllData()
    return client.request(API.logOut())
  }
}

The controller just uses login and logout methods of the service, while all the token handling is happening under the hood.

The question is, whether such use of Promises is correct, since I add specific logic only on success?

I've read about the Broken Chain antipattern, but would like to hear, whether the provided example is correct/incorrect way to handle such use-cases.

Thank you!
BR,
Richard

Swift 4.1 error: Ambiguous use of operator '=='

Hi,
I got an error when working with Swift 4.1 and Xcode 9.3 beta 3 (9Q117m), when installing the framework using CocoaPods v1.4.0:
image

Not critical now, stable Xcode 9.2 and Swift 4 work correctly.

Removing this piece of code makes it compile:

    static func == (lhs: When<Value?>, rhs: When<Value?>) -> Bool {
      switch (lhs, rhs) {
      case (.value(let lhs), .value(let rhs)):
        switch (lhs, rhs) {
        case (nil, nil):
          return true
        case (nil, _?), (_?, nil):
          return false
        case let (lhs?, rhs?):
          return lhs == rhs
        }
      case (.error(let lhs), .error(let rhs)):
        return (lhs as NSError).isEqual(rhs as NSError)
      case (.value, .error), (.error, .value):
        return false
      }
    }

Introduction of the conditional conformance in Swift 4.1 might be the root cause.

Cancellation Token

current code:

    public static func download(token: Cancellation.Token? = nil) -> Promise<Data> {
        return Promise { fulfill, reject in
            // simulate download ..., typically data will come in chunks and will be cached ...  
            DispatchQueue.main.asyncAfter(deadline: .now() + 2, execute: {
                if let token = token, token.isCancellationRequested {
                    return reject(Error.cancel)
                } else {
                    return fulfill(Data())
                }
            })
        }
    }
    let source = Cancellation.Source()
    
    let promise = download(token: source.token)
        .then({ (data) in
            print("data -----> ", data)
        })
        .catch({ (error) in
            print("ERROR -> ", error)
        })
    
    DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: {
        // simulate user pressed stop downloading ...
        source.cancel()
    })

proposal:

implement something like this: https://github.com/vadymmarkov/When#fail
or maybe reevaluate #31
Here is a sketch: https://gist.github.com/umbri/7413f4c9b41cfc210561e01b6165a23e

Other suggestions ?

How to make Promise without returned value?

Hello! Great framework! Please tell me how to do Promise without a return value? For example, I update the user name in firebase and I expect some value, but only check for an error. I now write Bool as a return value, although in fact I do not need it, how can this be done differently?

I would also like to know what is better to fix in this code for a more productive / readable code using the Promise framework. Thanks.

Sample code

    private func updateName(_ name: String) -> Promise<Bool> {
        let promise = Promise<Bool>(on: .global(qos: .default)) { fulfill, reject in
            guard let userID = UserRealmManager().getUser()?.id else {
                // TODO: - make custom error
                return
            }
            let ref = Database.database().reference().child(UsersPaths.Main.users.rawValue).child(userID)
            let data = [UsersPaths.UserProperties.displayName.rawValue : userID]
            ref.updateChildValues(data, withCompletionBlock: { (error, _) in
                if let error = error {
                    reject(error)
                } else {
                    fulfill(true)
                }
            })
        }
        return promise
    }

Changelogs for releases

Are there any plans to publish changelogs for the releases?
I have a project depending on Promises, and it's second time I inspect changes commit-by-commit to understand what's changed between versions. Quick summary of important changes (such as operator renames for 1.1.0) would be much appreciated.

implementation discussion: why to use dispatch_group_async along with dispatch_group_enter/leave?

I dug into the source, and found that you use dispatch_group_async along with dispatch_group_enter/leave, is this the right way to use GCD group?

image

I googled it and find an blog explaining the concept: Using dispatch groups to wait for multiple web services, it says use either dispatch_group_async OR dispatch_group_enter/leave.

Anyone can explain it?

If it is not appropriate to ask there, sorry for that, I will close it.

Swift library using Promise, methods not visible in ObjC

I have a (private) swift pod which exposes a lot of methods that return Promise. I'm trying to use those methods from an ObjC codebase and they aren't visible from there. They do become visible if I use FBLPromise instead. I understand that's because Promise doesn't extend from NSObject, or something similar.
My idea for a workaround is making analog methods that call the underlying swift api and return the asObjCPromise() of them, and mark those methods with NS_SWIFT_UNAVAILABLE. Is there any better aproach or something i'm not seeing?

Edit: I missed the fact that NS_SWIFT_UNAVAILABLE is an ObjC thing. I also have a greater problem that is that these methods are part of a protocol, and providing alternatives doesn't fix the problem t hat the protocol cannot be seen from objc.
Am i to either fall back and use FBLPromises in my swift code, of always use my library from swift?

Proposal: error handling with generic parameter

Hello :)

Idea : make a overloaded catch function with generic parameter

extension Promise {
    
@discardableResult
public func `catch`<ErrorType: Error>(on queue: DispatchQueue = .promises, _ reject: @escaping (ErrorType) -> Void) -> Promise {
    return self.catch(on: queue) { (error) -> Void in
        guard let typedError = error as? ErrorType else {
            return
        }
       reject(typedError)
   }
}

and using like

promiseFunction().catch { (error: MyError) in
    // error is MyError
}.catch { error in
    // default
}

instead of

promiseFunction().catch { error in
    if let myError = error as? MyError {
        // handling error
    }
}

Application not compiling on XCode 10 and on iOS 12 device

There seems to be an issue while converting Promise to FBLPromise. Completly blocked.

  1. While generating Objective-C header
  2. While printing 'Connection' at /Volumes/Official/WorkingCopy/native/Classes/Swift/Connection/Connection.swift:11:1
  3. While printing type 'Promise.ObjCPromise'
  4. While printing type 'Value'
    error: Segmentation fault: 11

CancelToken for promise completion blocks

Promises should have ability to remove registered fulfillment/rejection callbacks(blocks) WITHOUT influencing underlying operation that promise corresponds to.

Such CancelToken (often also called InvalidationToken) should also allow cancellation of callback scheduled on some queue from within the same queue, just in earlier block. In other words, cancellation of callback should work even if its block is already scheduled on the queue (but not yet started to execute).

Promises in Application Extension

Hi, is it possible to use Promises in Application Extensions (i.e. Siri Intents or Today Extension)?
I'm using Promises for my network layer which is shared using a framework.
The Promises library is used with the help of CocoaPods.

The app is organized in the following manner:
AppNameKit - Core framework with networking and logic
AppName - The application itelf
AppIntent - The Siri intent
AppIntentUI - The UI component of the Siri Intent.

While the framework is linked correctly and the app works fine, I got the error when I try to use the AppNameKit in AppIntent.

I can import Promises in the AppIntent, but whenever I use the code that actually uses Promise as its return value, I get the error:

ld: warning: linking against a dylib which is not safe for use in application extensions: /Users/richard/Library/Developer/Xcode/DerivedData/AppName-akvlogsasqbqhhgohvikypiqacwv/Build/Products/Debug-iphonesimulator/AppNameKit.framework/AppNameKit
ld: warning: Could not find auto-linked framework 'KeychainAccess'
ld: warning: Could not find auto-linked framework 'Kingfisher'
ld: warning: Could not find auto-linked framework 'Promises'
ld: warning: Could not find auto-linked framework 'FBLPromises'
ld: warning: Could not find auto-linked framework 'JWTDecode'
ld: warning: Could not find auto-linked framework 'Alamofire'
Undefined symbols for architecture x86_64:
  "static (extension in Promises):__C.OS_dispatch_queue.promises.getter : __C.OS_dispatch_queue", referenced from:
      default argument 0 of Promises.Promise.then(on: __C.OS_dispatch_queue, _: (A) throws -> ()) -> Promises.Promise<A> in PhoneBalanceIntentHandler.o
  "Promises.Promise.then(on: __C.OS_dispatch_queue, _: (A) throws -> ()) -> Promises.Promise<A>", referenced from:
      AppNameIntent.PhoneBalanceIntentHandler.handle(intent: AppNameKit.ViewBalanceIntent, completion: (AppNameKit.ViewBalanceIntentResponse) -> ()) -> () in PhoneBalanceIntentHandler.o
     (maybe you meant: _$S8Promises7PromiseC4then2on_ACyxGSo17OS_dispatch_queueC_yxKctFfA_)
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

image

What could be the reason for such result? What is the best way to use Promises in such a configuration (shared networking & logic core, multiple targets - app, extension, intents...)?

Are Promises safe to be used in App Extensions?

waitForPromises() should be removed

waitForPromises() should be removed because it is an abstraction leak: you never know in the test what other promises tested code will use in it internal implementation.

"So waiting for a bunch of async tasks to finish in a test can be tricky." (from docs) — no, it is tricky on Android that doesn't have any SDK support for it.

On iOS, we have XCTestExpectation exactly for that, without false hope for tested code to move into predictable state by leaking its implementation details into the test.

Unable to find a specification

I am trying to install this with cocoapods

I first set (as per doc) in my podfile,

pod 'PromisesObjC', '~> 1.2.3'

it gave me following error

Unable to find a specification for PromisesObjC (~> 1.2.3)

Then I tried with pod 'PromisesObjC'

it gave me following error

Unable to find a specification for PromisesObjC

I am using xcode 9.4

Could not cast value of type #MyClass to NSObject

I ran to this runtime error.
Does it mean my class has to be inherited from NSObject to be used as Promise type?

It stops at this library code

  static func asValue(_ value: AnyObject?) -> Value? {
    // Swift nil becomes NSNull during bridging.
    return value as? Value ?? NSNull() as AnyObject as? Value
  }

callstack :
...
#4 0x000000010f00ccfb in swift::swift_dynamicCastFailure(void const*, char const*, void const*, char const*, char const*) ()
#5 0x000000010f00cd60 in swift::swift_dynamicCastFailure(swift::TargetMetadataswift::InProcess const*, swift::TargetMetadataswift::InProcess const*, char const*) ()
#6 0x000000010f049d8e in swift_dynamicCastObjCClassUnconditional ()
#7 0x000000010f00f03d in swift_dynamicCast ()
#8 0x000000010f4eaf1a in swift_rt_swift_dynamicCast ()
#9 0x000000010f546f64 in specialized setDownCastConditional<A, B>(:) ()
#10 0x000000010f5478c2 in specialized static Set.conditionallyBridgeFromObjectiveC(:result:) ()
#11 0x000000010f4a792f in static Set.conditionallyBridgeFromObjectiveC(:result:) ()
#12 0x000000010f4a79a4 in protocol witness for static ObjectiveCBridgeable.conditionallyBridgeFromObjectiveC(:result:) in conformance Set ()
#13 0x000000010f0100cd in dynamicCastClassToValueViaObjCBridgeable(swift::OpaqueValue*, swift::OpaqueValue*, swift::TargetMetadataswift::InProcess const*, swift::TargetMetadataswift::InProcess const*, (anonymous namespace)::ObjectiveCBridgeableWitnessTable const*, swift::DynamicCastFlags) ()
#14 0x000000010946f02a in swift_rt_swift_dynamicCast ()
#15 0x000000010947eddd in static Promise.asValue(
:) at $projectpath/Pods/PromisesSwift/Sources/Promises/Promise.swift:104
#16 0x00000001094794d3 in closure #1 in Promise.then(on:
:) at $projectpath/Pods/PromisesSwift/Sources/Promises/Promise+Then.swift:90
#17 0x0000000109479a6d in partial apply for closure #1 in Promise.then(on:
:) ()
#18 0x000000010947823c in thunk for @escaping @callee_guaranteed (@owned Swift.AnyObject?) -> (@out Any?) ()
#19 0x000000010880567e in __56-[FBLPromise chainOnQueue:chainedFulfill:chainedReject:]_block_invoke.88 at $projectpath/Pods/PromisesObjC/Sources/FBLPromises/FBLPromise.m:271
#20 0x00000001088048f5 in __44-[FBLPromise observeOnQueue:fulfill:reject:]_block_invoke_2 at $projectpath/Pods/PromisesObjC/Sources/FBLPromises/FBLPromise.m:224

Thank you.

Promises vs Facebook Bolts-ObjC

First of all, many thanks for releasing promises, it looks extremely useful and I'm happy that we still see a few great Objective-C libraries in 2018.

I notice that you compare it with quite a few other promises libraries, but not with Facebook's Bolts-ObjC framework. Since that just came up on twitter I'd love to see a comparison/thoughts on how where the main differences are.

If issues are not the right place for these kind of questions, happy to close and post this somewhere else. Thanks!

Is it possible to have multiple observers for a single promise?

I use Promises in the data-driven iOS app to represent API endpoints.

An app has a case, when two independent views have to be updated based on a single API call. One of the views has a UIRefreshControl, the other one is passive, i.e. it cannot initiate a network call.

Is it possible to subscribe both views to the promise, while being able to initiate a network call only from one of them?

Here is the schema of what I'm trying to achieve:
image

Conceptually, it's very similar to hot/cold signals in Reactive approach. However, I wouldn't like to add an extra dependency to the app if it's used only at one place.

Promise+Retry.swift fails to build for swift version <= 4

When we are on swift version < 4.1 the predicateBlock has type
var predicateBlock: ((_ count: Int, _ error: Error) -> ObjCBool)?

This gives an error when used below in the onQueue call because the condition type is defined as:
typedef BOOL (^FBLPromiseRetryPredicateBlock)(NSInteger, NSError *)

Cannot convert value of type '((Int, Error) -> ObjCBool)?' to expected argument type '((Int, Error) -> Bool)?'

Can't use fulfill with Promise<Void>

Hi,

I can't figure out how to use fulfill with a Promise<Void>.

func doSomethingInBackground() -> Promise<Void> {
    return Promise<Void>(on: bgQueue) {
        fulfill, reject in
        myMoc.perform {
            fulfill() // compiler complains Missing argument for parameter #1 in call
        }
    }
}

fulfill(nil) doesn't work either.

What is your recommendation on how to initialize an async Promise which does not have a logical return value?

Is it possible to have default queue per Promise?

From what I understand, the default dispatch queue is global and for all Promise created.

Is it possible to have the default queue per Promise?

Supplied when creating a Promise instance and be as a default queue for all then/always/catch/recover closures for this Promise unless specified otherwise for that specific closure.

The rationale is the global default affects too many things. Different Promise should run on queue with different QoS. Usually I have a Promise which should run as DispatchQueue. userInitiated and it chains many then/always/catch/recover closures down the line which I want it to run in the same queue by default.

With current implementation, I have to pass the queue to every closures. And at the outmost Promise, I have then/always/catch closure on DispatchQueue.main to update UI.

Thanks.

What is the best way to retry a promise?

On the readme is says that using promises makes it easier to retry asynchronous operations. I couldn't
find a retry method or anything of the sort, so what would be the simplest way to retry an operation using promises?

Thanks.

Using Promises on an application extension

First of all thanks for this beautiful library! I have a small problem with it.

I am trying to use Promises in a network extension and getting these ld warnings:

ld: warning: linking against a dylib which is not safe for use in application extensions: /Users/umit/Desktop/code/meshkat_ios/Carthage/Build/iOS/FBLPromises.framework/FBLPromises
ld: warning: linking against a dylib which is not safe for use in application extensions: /Users/umit/Desktop/code/meshkat_ios/Carthage/Build/iOS/Promises.framework/Promises

According to documentation, submitting my app to iTunes Connect without clearing these warnings will cause a rejection.

https://developer.apple.com/library/archive/documentation/General/Conceptual/ExtensibilityPG/ExtensionScenarios.html

Again from documentation:

"To configure an app extension target to use an embedded framework, set the target’s “Require Only App-Extension-Safe API” build setting to Yes. If you don’t, Xcode reminds you to do so by displaying the warning “linking against dylib not safe for use in application extensions”."

Anyone seeing this asObjCPromise swiftc crash in Xcode 11

for this method:

  @objc
  public func allFoo() -> Promise<NSArray>.ObjCPromise<NSArray>
  {
    return promiseSwiftArrayOfFoo().then { $0 as NSArray }.asObjCPromise()
  }

Crashes swiftc with:

Showing All Messages

1.	While generating Objective-C header [redacted]
2.	While printing 'TheClass' at [redacted]/TheClass.swift:14:8
3.	While printing type 'Promise<NSArray>.ObjCPromise<NSArray>'
4.	While printing type 'Value'

Update, the original code which also crashes (I thought the above might be simpler for the type mangler to resolve):

  @objc
  public func allFoo() -> Promise<[Foo]>.ObjCPromise<NSArray>
  {
    return promiseSwiftArrayOfFoo().asObjCPromise()
  }

recover return error or nil

Hi, I'd like to use "recover" to catch errors and do some fallback function for specific error code. But I got errors in the recover block:

Return type 'NSError *' must match previous return type 'FBLPromise<NSMutableArray *> *' when block literal has unspecified explicit return type

Here's my sample.

[self doAWork]
.recover(^(NSError *error) {
    if (error.code == USE_FALLBACK) {
        return [self doFallback];
    } else {
        return error; // this will cause compile errors
    }
})
.then(^id(NSMutableArray *values) {
    return [self doBWork:values];
}).catch(^(NSError *error) {
    NSLog("something wrong. error= %@", error);
});

Is it possible to return error in "recover" block? Or are there any other ways I can try?
Thanks.

Discussion: RxSwift Benchmark vs. Promises

Congratulations on the release of the new Promise library! It looks great and the implementations seems extremely fast and efficient.

I've read the Benchmark you published and noticed RxSwift is one of the "Compared-against" libraries.

This isn't out of "blind love" of RxSwift (it has its flaws and strengths), but comparing a Promise library to a full-blown Rx implementation seems "unfair" or wrong in its basis.

I'd love to learn why you made the decision to compare against it specifically, since it is entirely not a Promise library at its basis (as opposed to PromiseKit or BrightFutures that specifically provide a solution for the "Promise" problem) .

Regardless, since I think all libraries benchmarked against "Google Promises" would love to improve their performance - I, for one, would appreciate it if you could publish the code you used to benchmark against each of the libraries, just so that developers get full clarity while library developers have the opportunity to find bottlenecks they might fix.

Appreciate your response and thoughts on this matter :)

Proposal: Concurrency for all, any, when

Proposal:

concurrency : UInt? = nil for all, any, when

ex: Lets say we want to make 1000 async requests, but with concurrency 10, i think this will be a useful feature

Add support for Each extension

While the All extension is useful for parallel execution of promises, it would be useful to also have a mechanism that ensures serial execution of promises.

Something like:

[FBLPromise each:@[p1, p2, p3, ...]] that returns a promise that is resolved when all supplied promises resolve in order.

See http://bluebirdjs.com/docs/api/promise.each.html for an example of how this might be handled.

I think copying Bluebird's behavior here is probably fine.

We basically want a mechanism where we can supply an array of promises, execute them one at a time serially, and then be able to chain an additional promise to be executed when this set of promises is done.

This kind of mechanism allows building more generalized chains, where you can have many serial chains executed in parallel (where you would wrap an array of "each" chains in an "all" chain), and parallels chains executed in serial order.

CocoaPods and Swift?

The instructions seem to explicitly exclude the idea of adding this via CocoaPods and using it with Swift. Is this the case? I gave it a shot and was told,

Could not build Objective-C module 'FBLPromises'

Instructions for running benchmarks

I maintain a not-so-popular Promise library for Swift, Bluebird.swift, which I'd like to benchmark against the same set of tests. Of the benchmarked libraries, I think my library (spoiler: directly based on Bluebird.js) is actually the most similar to the API in Promises.

all() with a generic tuple containing 4 types

The all() function currently supports tuples with up to 3 different types. Does it make sense to have an all() function that supports tuples with up to 4 types? I realize that if 4 types are supported, then someone might ask for 5 types! So, I understand if this request is denied.

As a workaround, I'm composing all within all, which isn't pretty: all(promise1, all(promise2, promise3, promise4)). FYI, though I'm using 4 promises, my code rarely (if ever) makes 4 I/O requests due to caching.

Required key CFBundleVersion in Info.plist

I try to upload my app and Distribution failed with erros:

  • ERROR ITMS-90056: This bundle .../Frameworks/Promises.framework is invalid. The Info.plist file is missign the required key: CFBundleVersion.

The "CFBundleVersion" exists in Info.plist, but is empty. I change manualy to "1" and uploaded my app sucessfuly.

Carthage version: 0.29.0
Promises version: 1.2.1
XCode version: 9.4

Too slow

I had implemented FBLPromiseAwait for firebase. It basically gets some data from firebase node and iterate for various condition. This takes around 15 seconds for 605 records, while iteration with normal firebase functions takes only 2 to 3 seconds i.e

[[[[[[FIRDatabase database] reference] child:USERS_TABLE] queryOrderedByChild:@"user_id"] queryEqualToValue:[[obj objectForKey:@"data"] objectForKey:@"user_id"]] observeSingleEventOfType:FIRDataEventTypeValue withBlock:^(FIRDataSnapshot * _Nonnull snapshot){ ..........

Please help me if I am implementing anything wrong

here is my sample code FBLPromiseAwait.

` FBLPromise<NSMutableArray *> *promise = [FBLPromise
onQueue:dispatch_queue_create(NULL, DISPATCH_QUEUE_SERIAL)
do:^id {
NSError *error;
NSDictionary *notifications = FBLPromiseAwait([self getSomeData], &error);

                                             NSArray*notification_keys = [notifications allKeys];
                                             
                                             for(int notification_count=0;notification_count<[notification_keys count ];notification_count++)
                                            
                                             {
                                                 
                                                 NSDictionary*obj = [notifications objectForKey:[notification_keys objectAtIndex:notification_count]];
                                                 
                                                 
                                                 
                                                
                                                 
                                                 NSString *notifType = [[obj objectForKey:@"data"] objectForKey:@"type"];
                                                 NSString *timeString = [[PBDateFormatter sharedFormatter] getCustomDateStringForChat:[NSDate dateWithTimeIntervalSince1970:[[[obj objectForKey:@"data"] objectForKey:@"timestamp"] longLongValue]/1000]];
                                                 NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:[[obj objectForKey:@"notification"] objectForKey:@"title"] attributes:@{NSFontAttributeName : [UIFont fontWithName:PINGBUDS_FONT_NORMAL size:12], NSForegroundColorAttributeName : [UIColor blackColor]}];
                                                 
                                                 
                                                 //SOMEREFERENCE,conversation/deleteByInitiatingUser
                                                 if([notifType isEqualToString:@"SOMEREFERENCE"] || [notifType isEqualToString:@"conversation/deleteByInitiatingUser"] )
                                                 {
                                                     
                                                     NSDictionary*userData = FBLPromiseAwait(
                                                                                             [FBLPromise async:^(FBLPromiseFulfillBlock fulfill, FBLPromiseRejectBlock __unused _) {
                                                         
                                                         
                                                         [[[[[[FIRDatabase database] reference] child:USERS_TABLE] queryOrderedByChild:@"user_id"] queryEqualToValue:[[obj objectForKey:@"data"] objectForKey:@"user_id"]] observeSingleEventOfType:FIRDataEventTypeValue withBlock:^(FIRDataSnapshot * _Nonnull snapshot){
                                                             
                                                             fulfill([[snapshot.value allObjects] firstObject]);
                                                             
                                                         }];
                                                         
                                                         
                                                     }], &error);
                                                     NSLog(@"\n promise user userData - %@",userData);
                                                     
                                                     
                                                     
                                                     
                                                     NSDictionary*skillFound = FBLPromiseAwait(
                                                                                               [FBLPromise async:^(FBLPromiseFulfillBlock fulfill, FBLPromiseRejectBlock __unused _) {
                                                         
                                                         [[[[[[FIRDatabase database] reference] child:SOME_TABLE] queryOrderedByChild:@"id"] queryEqualToValue:[[obj objectForKey:@"data"] objectForKey:@"skill_id"]] observeSingleEventOfType:FIRDataEventTypeValue withBlock:^(FIRDataSnapshot * _Nonnull snapshot){
                                                             
                                                             
                                                             NSLog(@"\n\n obj at moment - %@",obj);
                                                             
                                                             fulfill([[snapshot.value allObjects] firstObject]);
                                                             
                                                             
                                                         }];
                                                     }], &error);
                                                     
                                                     
                                                    [_dataSource addObject:model];
                                                     
                                                     
                                                     
                                                     //Ends : SOMEREFERENCE,conversation/deleteByInitiatingUser
                                                     
                                                 }
                                                 
                                               
                                            
                                                 else if([components[0] isEqualToString:@"XXX"]){}
                                                 else if([notifType isEqualToString:@"YYYY"]){}
                                                 else if([notifType isEqualToString:@"zzzz"]){}
                                                 else if([notifType isEqualToString:@"pppp"]){}
                                                 
                                                 
                                                 
                                                 
                                             }
                                             
                                            
                                             dispatch_async(dispatch_get_main_queue(), ^{
                                                 
                                                 [MBProgressHUD hideHUDForView:self.view animated:YES];
                                                 [self do_some_ui_stuff];
                                                 
                                                 
                                                 
                                             });
                                             
                                             
                                             
                                             
                                             if (error) {
                                                 return error;
                                             }
                                             
                                             return _dataSource;
                                             
                                             
                                         }];`

Error on installing

Error on installing with cocoapods:
[!] Unable to find a specification for PromisesSwift (~> 1.0)

Promises streams

Is it possible to implement a "stream" concept with Promises? What would be the recommended way?

There are many use cases where it is necessary to provide multiple invocations of the then block over the lifetime of a Promise:

  • In CoreBluetooth:
    -- multiple responses to a scan will occur if there is at least one eligible remote device in the vicinity
    -- multiple responses to a Notification request over extended time is the expected behaviour

Similar behaviour is found in CoreLocation.

SimpleFutures implements the concept of a FutureStream and PromiseStream using an array of responses up to a maximum defined by a capacity parameter. Maybe there is an need for history, maybe not. In the above cases, each new update would supersede all prior updates.

Invalidating a stream would be done either by a timeout (already implemented in Promises) or explicit invalidation by the application.

Any thoughts on this would be welcome.
ac

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.