▸ Friends ▸ Conversations Introducing: Stranger Chat > Hello Dustin Henderson. > You have 3 conversations: - [Lucas Sinclair] Skate with Max ? - [Will Byers] From the Upside Down - [Mike Wheeler] Secret about Eleven
guard error == nil else { print("Error:\(error!)") return } guard let token = token else { print("Received empty token ¯\\_(ϑ)_/¯") return } // Here we have the token. Ready for next step }
in guard error == nil else { print("Error:\(error!)") return } guard let token = token else { print("Received empty token ¯\\_(ϑ)_/¯") return } APIManager.shared.fetchUser(withToken: token, completion:{ (user, error) in guard error == nil else { print("Error:\(error!)") return } guard var user = user else { print("Received nil user ¯\\_(ϑ)_/¯") return } // Here we have the token. Ready for next step }) })
1976 … One solution: Promise Pattern A promise is an object that represents an asynchronous task. Pass that object around, and write clean, ordered code; a logical, simple, modular stream of progression from one asynchronous task to another.
Promise { fullfill, reject in do { let data = try makeNetworkCall() let result = try parseServerResponse(data) completion?(result, nil) } catch { completion?(nil, error) } } }
Promise { fullfill, reject in do { let data = try makeNetworkCall() let result = try parseServerResponse(data) fullfill(result) } catch { reject(error) } } }
succeed. ▸ when ▸ when(resolved:) - Call the next promise when all the promises have been executed. ▸ when(fullfiled:) - Call the next promise if all the promises succeed. ▸ catch ▸ When any promise of the chain failed. Call it
token in APIManager.shared.fetchUser(withToken: token) }.then { user -> Promise<([User], [Conversation])> in self.currentUser = user let friendsPromise = APIManager.shared.fetchFriends(forUserWithId: user.identifier) let conversationsPromise = APIManager.shared.fetchConversations(forUserWithId: user.identifier) return when(fulfilled: friendsPromise, conversationsPromise) }
token in APIManager.shared.fetchUser(withToken: token) }.then { user -> Promise<([User], [Conversation])> in self.currentUser = user let friendsPromise = APIManager.shared.fetchFriends(forUserWithId: user.identifier) let conversationsPromise = APIManager.shared.fetchConversations(forUserWithId: user.identifier) return when(fulfilled: friendsPromise, conversationsPromise) }.then { (friends, conversations) -> Void in print("Hello \(self.currentUser!.fullname).") print("You have \(conversations.count) conversations:") for conversation in conversations { let friend = friends.first(where: {$0.identifier == conversation.otherPeerId}) print("[\(friend?.fullname ?? "Unknow")] \(conversation.title)") } }.catch { (error) in print("We have an error, another failed experiment :( \(error)") }