使用 PromiseKit 的正确方法

Proper way to err out of PromiseKit

从这样的函数中抛出错误的正确方法是什么:

    func fetch(by id: String, page: Int = 1) -> Promise<ProductReviewBase> {
    // call api
    guard let url = URL(string: "") else {
        return Promise { _ in return IntegrationError.invalidURL }
    }

    return query(with: url)

}

我很困惑是让这个函数抛出错误,还是 return 承诺 return 是一个错误。谢谢

我真的很讨厌混合隐喻的界面。如果您要 return 承诺,请使用承诺的错误系统。如果你想要比我的仇恨更多的理由,那么想象一下它在呼叫站点会是什么样子:

do {
    (try fetch(by: id))
        .then {
            // do something
        }
        .catch { error in 
            // handle error
        }
}
catch {
    // handle error
}

fetch(by: id)
    .then {
        // do something
    }
    .catch { error in 
        // handle error
    }

后者看起来干净多了。

这是编写示例函数的最佳方式 (IMO):

func fetch(by id: String, page: Int = 1) -> Promise<ProductReviewBase> {
    guard let url = URL(string: "") else { return Promise(error: IntegrationError.invalidURL) }
    return query(with: url)
}