If I have one function which returns a promise and calls another function which also returns a promise, is it possible to convert between the two without doing this...
func f1() -> Promise<Any?> { ... }
func f2() -> Promise<Void> {
return f1().then { value -> Void in
...
}
}
Run Code Online (Sandbox Code Playgroud)
If I don't have the .then
call, the compiler cannot convert from one type to another.
假设我想生成一个需要多个承诺才能解决的数据集,我如何将每个结果存储在承诺链中,以便我可以一次性创建我的最终数据集?
struct CompleteData {
let a: String
let b: String
}
func getData() -> Promise<CompleteData> {
getA().then { a -> Promise<String> in
return a.getB()
}.then { b -> CompleteData in
return CompleteData(a: ???, b: b)
}
}
Run Code Online (Sandbox Code Playgroud)
我提出的解决方案不够优雅:
使用隐式解包的选项来存储临时值。如果我忘记分配给a
.
func getData() -> Promise<CompleteData> {
var a: String!
getA().then { _a -> Promise<String> in
_a = a
return _a.getB()
}.then { b -> CompleteData in
return CompleteData(a: a, b: b)
}
}
Run Code Online (Sandbox Code Playgroud)
从外部作用域嵌套承诺和访问值。这通过进入嵌套地狱而违背了 Promise 的目的。
func …
Run Code Online (Sandbox Code Playgroud) 是什么Void
在斯威夫特4是什么意思?如果我有一个函数fulfill
,如下:
func someFunc() -> Promise<Void> {
fulfill()
}
Run Code Online (Sandbox Code Playgroud)
显示错误,它仅在以下情况下有效:
fulfill(Void())
Run Code Online (Sandbox Code Playgroud)
注意.支持Swift 3:
fulfill()
Run Code Online (Sandbox Code Playgroud)
我正在使用Swift 4,但有人可以帮助解释为什么Void
在Swift 4中有一个构造函数吗?
我正在使用PromiseKit处理我的网络呼叫。我正在尝试查看是否有公约或更干净的方法尽早实现或拒绝诺言。如下所示,有一些条件要求我及早实现或拒绝。我目前正在通过在return
随后发表声明来做到这一点。我觉得这很笨拙,想知道是否有更好的方法可以做到这一点。谢谢!
return PromiseKit { fulfill, reject in
if statusCode == 200 {
if conditionA {
if conditionB {
fulfill(...) // How do I stop the execution chain from here
return
} else {
reject(...) // Or here, without having to call return every time
return
}
}
reject(...)
}
}
Run Code Online (Sandbox Code Playgroud) 根据迁移指南PromiseKit 6.x更改了有关catch
块的策略。在PMK 4中catch
返回了附加的承诺。现在catch
是一个终结者。我了解为什么要进行这些更改,但是...
在我的代码库(与PK4连接)中,我从catch
返回保证中获得了一些好处。
func loginAndSync(withServerAddress address: String, port: String) -> Promise<()> {
synchronizationService.stopAllRunningSingleSynchronizations()
return
authorizationService.save(serverAddress: address, andPort: port)
.then {
self.synchronizationService.startSingleFullSynchronization()
}
.then {
self.authorizationService.markAsServerSynced()
}
.catch { error in
log.error(error)
_ = self.authorizationService.markAsServerUnsynced()
}
}
Run Code Online (Sandbox Code Playgroud)
在此函数中,我提出了一些在某些情况下可能会失败的逻辑。万一发生错误,catch
块应该做出一些逻辑处理,但是我还要loginAndSync
将此承诺(履行或拒绝)的结果发送给函数的调用者。上面的函数可以由ViewController调用,例如,在ViewController中,我想显示错误或成功对话框。
这就是catch
一个Promise链需要两个ES 的原因。一为authorizationService
一UI
。
PromiseKit6中是否有解决方法来实现这一目标?
我发现了两个解决方案(解决方法)。我创建了两个答案以将它们分开。未来的读者可以决定哪个更好或提供新的。
我正在连续调用三个服务。当我调用第三个服务时,我需要使用第一个服务响应中的变量,即userModel
. 我可以从中获得第二个服务响应,initModel
但无法达到第一个模型userModel
。我的问题是 如何通过返回然后阻止在 done 块中使用 userModel ?
PS:我试图-> Promise<(UserModel,InstallationModel)>
在第一次调用时返回,但因为UserModel
已经是一个对象而不是一个承诺,我需要将它转换为承诺返回它。这看起来像我这样做的坏方法。
正如你所看到的,我正在存储它self.userModel = userModel
,我不想这样做。
func callService(completionHandler: @escaping (Result<UserModel>) -> Void) {
SandboxService.createsandboxUser().then { userModel -> Promise<InstallationModel> in
self.userModel = userModel
return SandboxService.initializeClient(publicKey: self.keyPairs.publicKey)
}.then { initModel -> Promise<DeviceServerResponseModel> in
self.initModel = initModel
if let unwrappedUserModel = self.userModel {
return SandboxService.deviceServerServiceCaller(authKey: initModel.token.token,apiKey:unwrappedUserModel.apiKey,privaKey: self.keyPairs.privateKey)
}
throw ServiceError.handleParseError()
}.then { serverResponseModel -> Promise<UserModel> in
if let unwrappedInitModel = self.initModel, let unwrappedUserModel …
Run Code Online (Sandbox Code Playgroud) 我试图做这个看似微不足道的事情:
static func list() -> Promise<[Activity]> {
let endpoint = "\(self.baseUrl)/v1/activities"
return Promise { fulfill, reject in
self.fetchHeaders { (headers) in
return Alamofire.request(
endpoint,
method: .get,
parameters: nil,
encoding: JSONEncoding.default,
headers: headers
).validate().responseJSON().then() { response in
guard let json = response as? JSON else {
reject(ActivityError.parse("Malformed JSON"))
}
guard let jsonActivities = json["activities"] as? [JSON] else {
reject(ActivityError.parse("Missing field"))
}
var activities: [Activity] = []
for jsonActivity in jsonActivities {
guard let activity = Activity(json: jsonActivity) else {
reject(ActivityError.parse("Unable to …
Run Code Online (Sandbox Code Playgroud) 在Swift PromiseKit库中,有一个使用有点奇怪语法的Alamofire示例:
func login(completionHandler: (NSDictionary?, ErrorProtocol?) -> Void {
Alamofire.request(.GET, url, parameters: ["foo": "bar"])
.validate()
.responseJSON { response in
switch response.result {
case .success(let dict):
completionHandler(dict, nil)
case .failure(let error):
completionHandler(nil, error)
}
}
}
Run Code Online (Sandbox Code Playgroud)
response
是一个描述两个具有相关值的案例的Alamofire枚举:
public enum Result<Value> {
case success(Value)
case failure(Error)
(...)
Run Code Online (Sandbox Code Playgroud)
我没有得到的是let
每case:
行中的含义以及dict(或错误)来自何处?这种语法糖是否更加冗长但不那么令人困惑?
我目前正在研究是否应该将 PromiseKit 集成到现有项目中。
我的主要问题是我需要实现一个可以调用最多 5 个 Web 服务的业务逻辑。其中一些是根据之前的结果来调用的。
我当前的架构基于将代码分解为多个函数,并使用相互调用的闭包。
我试图找出是否可以使用 PromiseKit (或其他任何东西)编写更易于管理的代码。
这是我需要完成的一些伪代码:
// if true, the phone validation is skipped
let forceRequest = false
// true if a 3rd party web-service has checked the phone number
let isVerified = true
// true if the 3rd party checked the phone number and it is valid
var isValid = false
if !isVerified {
// update value from 3rd party web-service
isValid = isValidPhoneNumberPromise()
}
// If the phone no is invalid …
Run Code Online (Sandbox Code Playgroud) 我正在使用 AlamoFire 和 PromiseKit 进行 API 调用。
代码运行良好 2 年,直到我更新到 Xcode 12.0。
函数现在返回错误:“无法将‘DataRequest’类型的值转换为关闭结果类型‘Void’”
我的功能如下:
func fetchArticlesFromApi (API: String) -> Promise<[Article]> {
return Promise<[Article]> { seal in
return Alamofire.request(API).validate().responseString(completionHandler: { //Error happening here
response in
switch (response.result) {
case .success(let responseString1):
//Do something
case .failure(let error):
print (error)
seal.reject(error)
}
})
}
}
Run Code Online (Sandbox Code Playgroud)
错误发生在函数的第三行 有什么想法可能在此更新中发生了变化?
注意:当我在 xcode 11.6 上运行相同的代码时,代码工作正常!
promisekit ×10
swift ×9
ios ×6
alamofire ×3
promise ×3
xcode ×2
asynchronous ×1
swift4 ×1
void ×1