Swift51.com
Swift 头像
Swift  2016-08-23 22:10

Swift 执行异步代码框架 BrightFutures

回复:0  查看:4593  感兴趣:12  赞:0  

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
}

相关开源代码