Swift 执行异步代码框架 BrightFutures。
我们经常会遇到写异步代码的情况,比如在等待网络响应后更新UI,或者在要执行耗时很长的运算后更新UI,通常我们会写类似下面的代码:
User.logIn(username, password) { user, error in
if !error {
Posts.fetchPosts(user, success: { posts in
// do something with the user's posts
}, failure: handleError)
} else {
handleError(error) // handeError is a custom function to handle errors
}
}
使用BrightFutures后,代码将是这样的:
User.logIn(username,password).flatMap { user in
Posts.fetchPosts(user)
}.onSuccess { posts in
// do something with the user's posts
}.onFailure { error in
// either logging in or fetching posts failed
}