objective-c - 对象 PromiseKit : Add new promises from within a promise

标签 objective-c asynchronous promisekit

我正在使用 PromiseKit只是我的 API 请求。

在这种情况下,我从服务器获取对象 ID 列表。然后我需要获取每个 ID 的详细信息,并返回一个详细信息数组。相当常见的场景。

实际上,我需要从第一个 promise 中包含的 FOR 循环中向 promise 链添加 promise 。

我创建的代码开始向右漂移,但链在第二条 promise 链(填充浅层模型请求)可以执行之前完成。

[PMKPromise promiseWithResolver:^(PMKResolver resolve) {
    // Fetch an array of object IDs (shallow objects)
    [APIManager fetchObjectListWithCompletion:^(NSArray *resultObjects, NSError *error) {
        resolve(error ?: resultObjects[0]);
    }];
}].then(^(NSArray *objects){
    // Fill each shallow object (query details)
    PMKPromise *fetches = [PMKPromise promiseWithValue:nil];
    for(id model in objects) {
      fetches.then(^{
            [APIManager fillShallowObject:model withCompletion:^(NSArray *resultObjects, NSError *error) {
              // resolve?
            }];
        });
    }

    // Return promise that contains all fill requests
    return fetches; 
})].then(^{
    // This should be executed after all fill requests complete
    // Instead it's executed after the initial ID array request
});

有没有更好的方法来完成我想要完成的事情?也许是一种用解析器附加 promise (.then) 的方法?

最佳答案

我想你想要 when:

[AnyPromise promiseWithAdapterBlock:^(id adapter) {
    [APIManager fetchObjectListWithCompletion:adapter];
}].then(^(id objects){
    NSMutableArray *promises = [NSMutableArray new];
    for (id model in objects) {
        id promise = [AnyPromise promiseWithAdapterBlock:^(id adapter){
            [APIManager fillShallowObject:model withCompletion:adapter];
        }];
        [promises addObject:promise];
    }
    return PMKWhen(promises);
}).then(^(NSArray *results){
    // when waits on all promises
});

代码是 PromiseKit 3。

关于objective-c - 对象 PromiseKit : Add new promises from within a promise,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38445718/

相关文章:

javascript - Javascript 数组排序是异步的吗?

javascript - Async/Await in fetch() 如何处理错误

swift - PromiseKit firSTLyOn 样式方法

ios - PromiseKit 取消 promise

swift - 错误 : cannot convert value of type '() -> ()' to closure result type 'String' using Swift + PromiseKit

ios - 适当的 UI 元素隐藏

iphone - 将文件从 iphone 应用程序发送到本地服务器?

c# - 异步等待新线程的行为

objective-c - 选择器 Objective-C 设置

iphone - ASIHTTPRequest 与 AFNetworking 框架