Skip to content

Instantly share code, notes, and snippets.

@mosluce
Created October 12, 2016 07:26
Show Gist options
  • Save mosluce/43d3133f64aa23013231176e98144462 to your computer and use it in GitHub Desktop.
Save mosluce/43d3133f64aa23013231176e98144462 to your computer and use it in GitHub Desktop.
//
// ViewController.swift
// Promise
//
// Created by 默司 on 2016/10/12.
// Copyright © 2016年 默司. All rights reserved.
//
import UIKit
import PromiseKit
import AwaitKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func request(url: String) -> Promise<Data?> {
return Promise { (resolve, reject) in
URLSession.shared.dataTask(with: URL(string: url)!) {data,res,error in
if let error = error {
return reject(error)
}
resolve(data)
}.resume()
}
}
func stop(sec: Int) -> Promise<Void> {
return Promise(resolvers: { (resolve, _) in
DispatchQueue.global().asyncAfter(deadline: .now() + .seconds(sec)) {
resolve()
}
})
}
@IBAction func asyncWork(_ sender: AnyObject) {
async {
print("start")
do {
try await(self.stop(sec: 5))
let data = try await(self.request(url: "https://news.baidu.com/"));
print("end")
print("============")
print(data)
print("============")
} catch {
print(error)
}
}
}
@IBAction func anotherWork(_ sender: AnyObject) {
print("click!")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment