Nested Firebase Completion Blocks

若如初见. 提交于 2019-12-11 16:14:05

问题


Recently I have been developing an app which requires the following code:

/** Unfriends the user with the specified UID */
func removeFriend(_ userID: String, completion: CompletionHandler? = nil) {
    CURRENT_USER_FRIENDS_REF.document(userID).delete { (error) in
        guard error == nil else{
            completion?(error)
            return
        }

        self.users.document(userID).collection(NameFile.Firebase.UserDB.friends).document(AppStorage.PersonalInfo.uid).delete(completion: completion)
    }
}

The problem arises in nesting these blocks. If the first blocks succeeds, but the second block throws an error, the completion handler will be passed an error. However, in reality, half the process succeeded and wrote successfully to database. Is it possible to have both these blocks work together as one block which passes an error if an error occurs. (without restructuring the database)


回答1:


If you have multiple write operations that must either call succeed or all fail, you should use a transaction or batched write. The difference between the two is whether you need the current value of a document to determine its new value. If you don't need the current value for any document, use a batched write. If you do need the current value for a document, use a transaction for all writes.



来源:https://stackoverflow.com/questions/51353239/nested-firebase-completion-blocks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!