Skip to content

Promise chaining base on condition #1185

Closed

Description

@zhouhao27

In most case, there is only one error catch and chain for the successful operation. But for my case, what I want to do is if the operation success, then I'll return. If it's failed, I'll do another operation. Is it possible and how to express it in PromiseKit?

For example, how to convert this pseudo code to PromiseKit way?

    fetchData1(fromURL: "someURL") { (response, results, error) in
            switch response {
            case .success:
                if !data.isEmpty() {
                   // complete
                } else {
                    fetchData2(for: results) { (response, results, error) in
                        switch response {
                        case .success:
                            // complete
                        }
                    case .fail:
                            // complete with error
                    }
             }
            case .fail:
                    fetchData2(for: results) { (response, results, error) in
                        switch response {
                        case .success:
                            // complete
                        }
                    case .fail:
                            // complete with error
                    }        
            }
        }

Activity

  1. GarthSnyder commented on Jan 24, 2021

    @GarthSnyder
    Collaborator

    This is a common pattern.

    fetchData1 and fetchData2 should follow the general guidelines for creating promise-based APIs: they should be methods that return a promise that either yields a value or errors out. Let the caller handle dealing with the errors.

    Something roughly like:

    func fetchData1(fromURL: "someURL") -> Promise<MyData> { 
        return initialDataFetch(for: results)
            .get { data in
                if data.isEmpty() {
                    throw MyFetch.badInitialData
                }
            }.recover { fetchData2(for: results) }
    }
    

    Here, initialDataFetch can be a separate method or just a firstly block.

  2. Repository owner locked and limited conversation to collaborators on Jan 30, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions