Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using PromiseKit to force sequential download

I am using PromiseKit and would like to force sequential download of JSONs. The count of JSONs might change.

I have read this about chaining. If I had a fixed number of say 3 downloads, this would be fine.

But what if I had a changing count of download that I would like to download sequentially?

This is my code for 2 URLs. I wonder how I could do this with dateUrlArray[i] iteration over the array?

 - (void)downloadJSONWithPromiseKitDateArray:(NSMutableArray *)dateUrlArray {
    [self.operationManager GET:dateUrlArray[0]
                    parameters:nil]
    .then(^(id responseObject, AFHTTPRequestOperation *operation) {
        NSDictionary *resultDictionary = (NSDictionary *) responseObject;
        Menu *menu = [JsonMapper mapMenuFromDictionary:resultDictionary];
        if (menu) {
            [[DataAccess instance] addMenuToRealm:menu];
        }
        return [self.operationManager GET:dateUrlArray[1]
                               parameters:nil];
    }).then(^(id responseObject, AFHTTPRequestOperation *operation) {
        NSDictionary *resultDictionary = (NSDictionary *) responseObject;

        Menu *menu = [JsonMapper mapMenuFromDictionary:resultDictionary];
        if (menu) {
            [[DataAccess instance] addMenuToRealm:menu];
        }
    })
    .catch(^(NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self handleCatchwithError:error];
        });
    }).finally(^{
        dispatch_async(dispatch_get_main_queue(), ^{
            DDLogInfo(@".....finally");
        });
    });
}
like image 477
brainray Avatar asked Jun 07 '15 09:06

brainray


2 Answers

The concept you're looking for is thenable chaining. You want to chain multiple promises in a for loop.

My Objective-C is really rusty - but it should look something like:

// create an array for the results
__block NSMutableArray *results = [NSMutableArray arrayWithCapacity:[urls count]];
// create an initial promise
PMKPromise *p = [PMKPromise promiseWithValue: nil]; // create empty promise
for (id url in urls) {
    // chain
    p = p.then(^{
        // chain the request and storate
        return [self.operationManager GET:url
                parameters:nil].then(^(id responseObject, AFHTTPRequestOperation *operation) {
              [results addObject:responseObject]; // reference to result
              return nil; 
        });
    });
}
p.then(^{
    // all results available here
});
like image 190
Benjamin Gruenbaum Avatar answered Oct 16 '22 16:10

Benjamin Gruenbaum


For those of us looking for a Swift 2.3 solution:

import PromiseKit

extension Promise {
    static func resolveSequentially(promiseFns: [()->Promise<T>]) -> Promise<T>? {
        return promiseFns.reduce(nil) { (fn1: Promise<T>?, fn2: (()->Promise<T>)?) -> Promise<T>? in
            return fn1?.then({ (_) -> Promise<T> in
                return fn2!()
            }) ?? fn2!()
        }
    }
}

Note that this function returns nil if the promises array is empty.

Example of use

Below is an example of how to upload an array of attachments in sequence:

func uploadAttachments(attachments: [Attachment]) -> Promise<Void> {
    let promiseFns = attachments.map({ (attachment: Attachment) -> (()->Promise<Void>) in
        return {
            return self.uploadAttachment(attachment)
        }
    })
    return Promise.resolveSequentially(promiseFns)?.then({}) ?? Promise()
}

func uploadAttachment(attachment: Attachment) -> Promise<Void> {
    // Do the actual uploading
    return Promise()
}
like image 6
Vegard Avatar answered Oct 16 '22 14:10

Vegard