问题描述
我有一个基于 Vapor 应用的非常简单的服务。该服务使用来自另一个服务系列的数据。显然,这正是 map
方法所针对的那种应用程序。
链中的所有回调都执行,但链中的最后一个 EventLoopFuture
永远不会完成,导致我的服务无限期挂起。
此代码进行一次异步调用以获取会话 ID,然后使用该数据检查某人是否是特定组的成员。对其他服务的调用返回合理的值 - 目前第二次调用总是返回错误。
请注意,在此代码片段中,我已经“解开”了序列的各个阶段,以尝试找出问题出现的位置,但整体行为不受影响。
我尝试了许多不同的链排列,在适当的情况下使用 flatMap
、map
和 flatMapError
,而没有改变最终结果。
let authService = remoteapi.authServices();
// EventLoopFuture<String> with sessionId
let sessionIdFuture = authService.getSessionId(username: userName,password: password)
// EventLoopFuture<Bool> with whether the user is in a particular group
let gsFuture = sessionIdFuture.flatMap { sessionId -> EventLoopFuture<Bool> in
let groupMemberService = remoteapi.groupMemberServices()
return groupMemberService.personIsInGroup(sessionId: sessionId,groupId: groupId,userId: userId)
}
// EventLoopFuture<Bool> if the above has an error,just return false
let errorFuture = gsFuture.flatMapErrorThrowing { error in
// This executes successfully!
return false
}
// EventLoopFuture<String> with the return data
let returnFuture = errorFuture.flatMapThrowing { isMember -> String in
// This executes successfully!
let response = PersonIsMemberResponse(isMember: isMember)
if let json = self.encodeResponse(response) {
print(json) // {"isMember": false}
return json
} else {
throw Abort(.internalServerError,reason: "Could not encode our own dang data type");
}
}.always { result in
// This executes!
do {
try remoteapi.shutdown()
} catch {
print(error)
}
}
gsFuture.whenComplete { result in
// This executes!
print("gsFuture complete!")
}
errorFuture.whenComplete { result in
// This executes!
print("errorFuture complete!")
}
returnFuture.whenComplete { result in
// This DOES NOT execute!
print("returnFuture complete!")
}
我看不到最后一个 flatMapThrowing
怎么能被执行并返回一个值,那么未来就没有完成。我错过了什么?
解决方法
正如我们在评论中共同发现的那样,看起来 try remoteApi.shutdown()
正在阻止任何进一步的事情发生。