0

I'm using PromiseKit 6 to make async requests. Think paginated requests:

api/v1/resource?
api/v1/resource?offset=5
api/v1/resource?offset=10
...
api/v1/resource?offset=50

What I do currently is this:

let paginatedResources: [Promise<Car>] = (0...<50).map({
  self.getPaginatedCar(offset: $0)
})
when(fulfilled: paginatedResources).compactMap { cars in
  print(cars)
}

This works fine and all, but now my pages are going be a lot higher than this (think like 100 paginated requests that need to be done). This causes a problem because as I make too many requests at a same time, more and more of them fail. I want to maybe break that down a little bit.

For example, if I have to make 100 requests, I'll probably chunk them to 10 requests at a time. How do I chain my when(fulfilled:)?

I'm thinking something like, but it's obviously not the right way to do this...

when(fulfilled: paginatedResources).compactMap { p in
  when(fulfilled: paginatedResources).compactMap { p in
    when(fulfilled: paginatedResources).compactMap { p in
      when(fulfilled: paginatedResources).compactMap { p in
        when(fulfilled: paginatedResources).compactMap { p in
        }
      }
    }
  }
}
7ball
  • 2,183
  • 4
  • 26
  • 61
  • 1
    Why make so many requests if the thing is paginated? Just make one large request with the large amount of data you want (large page size).. Otherwise I guess you can use `dispatch_group` and chunk the requests or use a queue and queue requests.. or maybe with promise you can for-loop it? Maybe if you tell us what problem you're trying to solve, we can help better.. Why do you need all this data at once when the request is paginated? – Brandon Mar 08 '18 at 01:42
  • Understood, but this is the way it is going to be done and I don't see it being changed anytime soon. Plus it's a useful thing to know for PromiseKit anyway. – 7ball Mar 08 '18 at 01:44
  • You want the other requests to start when the previous one finishes? – Brandon Mar 08 '18 at 01:45
  • Yes, say I want to wait for the first 10 to finish, then do the next 10, then the next 10 after that, and so forth. – 7ball Mar 08 '18 at 01:48
  • Would this: https://pastebin.com/GbxgDKFM . work for you? It chains just fine.. You can for-loop it so you don't have to type out all the thens.. https://pastebin.com/gcAGtbyk – Brandon Mar 08 '18 at 02:22

0 Answers0