Sequential Chained Requests with Siesta and Swift

By · Published · swift

Siesta is a framework for Swift that dramatically simplifies working with RESTful APIs. And like many things in Swift, it is natively built around asynchronous execution. It may fire any number of requests back, and they may complete in any order that is undefined.

But sometimes, you need to execute things in a specific order. Like when the result of one call will change subsequent calls. A classic example of this is an API where you might need to create a folder first, then upload files into the folder you created. So the folder creation needs to happen first, then the file uploads can happen after.

Natively, Siesta does not seen to support this mode of operation, at least not that I could find clearly documented. But with a little Swift magic using callbacks, we can get very close to this same functionality.

struct File {
    var data: Data?

func doUpload() {
    func chainRequests(queue: [File], finalCompletion: @escaping ()->()) {
        guard let item = queue.first else {

        let request = resource
            .request(.post, data:, contentType: "application/json")
            .onSuccess({ (entity) in
                if let o = entity.content as? File {
                    // Do stuff here, perhaps walk the remaining items in 
                    // the queue and update them.

                    chainRequests(queue: Array(queue[1 ..< queue.count]), finalCompletion: finalCompletion)

    chainRequests(queue: uploadFiles) {
        // Do stuff here, when we're all done sequentially completing the 
        // above items.

What we're doing here is sequentially executing each File upload in the queue, waiting until we receive a successful response from the previous one before continuing to the next item in the queue. At each successful completion, the queue shrinks until there's nothing left. Then we execute the finalCompletion handler to do any cleanup work.

( Comments )

Did something I wrote help you out?

That's great! I don't earn any money from this site - I run no ads, sell no products and participate in no affiliate programs. I do this solely because it's fun; I enjoy writing and sharing what I learn.

All the same, if you found this article helpful and want to show your appreciation, here's my wishlist.

Related Posts

Creating Traits or Mixins in Swift

Debugging the Responder Chain in Swift

comments powered by Disqus