Skip to content

Instantly share code, notes, and snippets.

View dimebt's full-sized avatar
🎯
Focusing

Dimitar Stefanovski dimebt

🎯
Focusing
View GitHub Profile
fetchJSON(fromURL: "http://api.json") { (json, error) in
}
fetchJSON(fromURL: "someURL") { (response, results, error) in
switch response {
case .success:
fetchUserData(for: results) { (response, results, error) in
switch response {
case .success:
loginUser(user: results) { (response, results, error) in
switch response {
case .success:
// finialy all of the callbacks are finished
fetchJSON(fromURL: "someURL") { (response, results, error) in
}
func promiseFetchJSON() -> Promise<[String: Any]> {
return Promise<[String: Any]> { seal in
fetchJSON(fromURL: "someURL", completion: { (response, results, error) in
switch response {
case .success:
seal.fulfill(results)
case .fail:
seal.reject(error)
}
})
func promiseFetchJSON() -> Promise<[String: Any]> {
return Promise<[String: Any]> { seal in
fetchJSON(fromURL: "someURL", completion: { (response, results, error) in
switch response {
case .success:
seal.fulfill(results)
case .fail:
seal.reject(error)
}
})
func promiseFetchUserData(user: [String: Any]) -> Promise<User> {
return Promise<User> { seal in
fetchUserData(for: user, completion: { (response, results, error) in
switch response {
case .success:
seal.fulfill(results)
case .fail:
seal.reject(error)
}
})
firstly {
promise1()
}.then {
promise2()
}.then {
promise3()
}.ensure {
// something that should happen whatever the outcome
}.done {
// all promises are resolved
firstly {
promiseFetchJSON()
}.then { (json) in
promiseFetchUserData(user: json)
}.then { (user) in
promiseLoginUser(user: user)
}.ensure {
// something that should happen whatever the outcome
}.done { (success) in
// all promises are resolved
private func downloadPhotos() {
// 1. Show preloading animation
self.activityIndicator.startAnimating()
// 2. Fetch and serialize json response
Alamofire.request(photosURL, method: .get).validate().responseData { (data) in
guard let data = data.result.value else { return }
guard let photos = try? JSONDecoder().decode([Photo].self, from: data) else { return }
// 3. Download photos
for photo in photos {
guard let photoUrl = URL(string: photo.url) else { return }
private func function() -> Promise<T> {
return Promise<T> { seal in
}
}