使用PromiseKit强制顺序下载 [英] Using PromiseKit to force sequential download

查看:151
本文介绍了使用PromiseKit强制顺序下载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我已阅读有关链接的
如果我有3个固定数量的下载量,那就没关系了。

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?

这是我的2个URL的代码。我想知道我怎么能用 dateUrlArray [i] 对数组进行迭代?

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


推荐答案

您正在寻找的概念for是然后能够链接。你想在for循环中链接多个promises。

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

我的Objective-C真的很生疏 - 但看起来应该是这样的:

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

这篇关于使用PromiseKit强制顺序下载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆