使用PromiseKit强制顺序下载



我正在使用PromiseKit,并希望强制json的顺序下载。json的数量可能会改变。

我读过这篇关于连锁的文章。如果我的下载量是固定的,比如3次,那就可以了。

但是,如果我有一个不断变化的下载计数,我想按顺序下载呢?

这是我的代码2 url。我想知道如何对数组进行dateUrlArray[i]迭代?

 - (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");
        });
    });
}

您正在寻找的概念是then可链接。你想在for循环中链接多个承诺。

我的Objective-C真的很生疏-但它应该看起来像:

// 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
});

对于那些正在寻找Swift 2.3解决方案的人:

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!()
        }
    }
}

注意,如果promises数组为空,这个函数返回nil

使用示例

下面是一个如何按顺序上传附件数组的示例:

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()
}

感谢Vegard的回答,我将为Swift 3重写:

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!()
        }
    }
}

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

最新更新