我正在尝试使用BrightFutures在SwiftExpress中创建一个基本的异步示例,并且失败了。这就是我所拥有的:
class FileSystem {
class func read(fileURL:NSURL, convert:(NSData?) -> Action<AnyContent>) -> Future<Action<AnyContent>, AnyError> {
let promise = Promise<Action<AnyContent>, AnyError>()
Queue.global.async {
let fileData = NSData(contentsOfURL:fileURL)
let action = convert(fileData)
promise.success(action)
}
return promise.future
}
}
这是服务器:
import Express
import TidyJSON
import BrightFutures
import Result
let app = express()
app.views.register(JsonView())
// Parameters: JSON object {"filePath" : "<filePath>"}
app.post("/readFile") { request -> Future<Action<AnyContent>, AnyError> in
//check if JSON has arrived
guard let json = request.body?.asJSON(),
let jsonDict = json.object,
let filePath = jsonDict["filePath"],
let filePathString = filePath.string else {
return future {
var response = [
"status": "error",
"message" : "Invalid request"
]
return Result(value: Action.render(JsonView.name, context: response))
}
}
print("json: \(json)")
print("json: \(json.object)")
let url = NSURL(fileURLWithPath: filePathString)
return FileSystem.read(url, convert: { data -> Action<AnyContent> in
var response = [String:AnyObject]()
var status:String
if data == nil {
status = "error"
response["message"] = "Could not read file"
}
else {
status = "ok"
response["result"] = data!
}
response["status"] = status
return Action.render(JsonView.name, context: response)
}).onSuccess { action in
print("action: \(action)")
}
}
app.all("/*") { request in
return Action.ok("Got a unknown request.")
}
app.listen(9999).onSuccess { server in
print("Express was successfully launched on port", server.port)
}
app.run()
当我使用Postman连接到此时,我得到一个“{}”作为回应。我可以设置断点,我知道代码正在执行,我知道我有一个错误(它无法找到文件 - 我本人故意),只是看不出为什么响应没有错误状态和消息。想法?
答案 0 :(得分:1)
问题解决了!单行错了:
var response = [String:AnyObject]()
需要:
var response = [String:String]()