如何顺序执行两个异步函数
How to execute two asynchronous functions sequentially
func getTopicIdFromMYSQL(){
let myUrl = NSURL(string: "xxxx")
let request = NSMutableURLRequest(URL: myUrl!)
request.HTTPMethod = "POST"
let email:String = "xxx@gmail.com"
let postString = "email=\(email)"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request){
data, response, error in
if(error != nil){
print("Get all topic")
print("error=\(error)")
return
}
do {
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSDictionary
if let parseJSON = json
{
let resultValue = parseJSON["status"] as? String
print("Get all topic")
favouriteTopic = parseJSON["getResult"]! as! [AnyObject]
print("return topic:\(favouriteTopic)")
dispatch_async(dispatch_get_main_queue(), {
if(resultValue == "Success"){
}
else{
let error = UIAlertController(title: "Error", message: "Please check your network configuration!:-(", preferredStyle: .Alert)
let cancel = UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)
let ok = UIAlertAction(title: "OK", style: .Default, handler: nil)
error.addAction(cancel)
error.addAction(ok)
}
})
}
}catch
{
print(error)
}
}
task.resume()
}
我已经得到了这段代码,但是,我想 运行 在它之后添加另一个函数。我应该怎么办。喜欢:
getTopicIdFromMYSQL()
getCommentFromMYSQL()
print("Finish")
我发现问题是我的代码没有按顺序执行,getCommentFromMYSQL函数和getTopicIdFromMYSQL差不多,我想运行这三个按顺序执行怎么办?
代码总是按顺序执行。我认为你的问题是你在这一行中进行异步调用:
NSURLSession.sharedSession().dataTaskWithRequest(request)
但是,由于代码是按顺序执行的,因此在异步调用完成之前会调用方法 getCommentFromMYSQL()
。你应该在这个条件中调用 getCommentFromMYSQL()
:
if (resultValue == "Success") {
}
或者任何你想要的时候。这将确保在第一个方法完成执行后调用方法 getCommentFromMYSQL()
。
这是因为,您正在后台线程中进行异步调用,运行。
如果要顺序执行,分派到主队列后调用next方法,
dispatch_async(dispatch_get_main_queue(), {
//call here
getCommentFromMYSQL()
if(resultValue == "Success"){
}
else{
let error = UIAlertController(title: "Error", message: "Please check your network configuration!:-(", preferredStyle: .Alert)
let cancel = UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)
let ok = UIAlertAction(title: "OK", style: .Default, handler: nil)
error.addAction(cancel)
error.addAction(ok)
}
})
将完成处理程序作为参数添加到您的异步函数:
func getTopicIdFromMYSQL(completion: (AnyObject?, ErrorType?)->())
func getCommentFromMYSQL(completion: (AnyObject?, ErrorType?)->())
注:
完成处理程序 必须 在异步函数完成时最终被调用 - 要么出现错误,要么出现计算值。
然后调用这些函数,如下所示:
getTopicIdFromMYSQL() { (result1, error) in
if let result1 = result1 {
// process result1
// ...
getCommentFromMYSQL() { (result2, error) in
if let result2 = result2 {
// process result2
// ...
} else {
// handle error
}
}
} else {
// handle error
}
}
您可以按如下方式实现这些功能:
func getTopicIdFromMYSQL(completion: (AnyObject?, ErrorType?) {
let myUrl = NSURL(string: "xxxx")
let request = NSMutableURLRequest(URL: myUrl!)
request.HTTPMethod = "POST"
let email:String = "xxx@gmail.com"
let postString = "email=\(email)"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request){
data, response, error in
if error != nil {
completion(nil, error)
}
do {
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSDictionary
if let parseJSON = json {
let resultValue = parseJSON["status"] as? String
print("Get all topic")
favouriteTopic = parseJSON["getResult"]! as! [AnyObject]
completion(favouriteTopic, nil)
} else {
throw MyError.Error(message: "bogus JSON")
}
} catch let error {
completion(nil, error)
}
}
task.resume()
}
func getTopicIdFromMYSQL(){
let myUrl = NSURL(string: "xxxx")
let request = NSMutableURLRequest(URL: myUrl!)
request.HTTPMethod = "POST"
let email:String = "xxx@gmail.com"
let postString = "email=\(email)"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request){
data, response, error in
if(error != nil){
print("Get all topic")
print("error=\(error)")
return
}
do {
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSDictionary
if let parseJSON = json
{
let resultValue = parseJSON["status"] as? String
print("Get all topic")
favouriteTopic = parseJSON["getResult"]! as! [AnyObject]
print("return topic:\(favouriteTopic)")
dispatch_async(dispatch_get_main_queue(), {
if(resultValue == "Success"){
}
else{
let error = UIAlertController(title: "Error", message: "Please check your network configuration!:-(", preferredStyle: .Alert)
let cancel = UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)
let ok = UIAlertAction(title: "OK", style: .Default, handler: nil)
error.addAction(cancel)
error.addAction(ok)
}
})
}
}catch
{
print(error)
}
}
task.resume()
} 我已经得到了这段代码,但是,我想 运行 在它之后添加另一个函数。我应该怎么办。喜欢:
getTopicIdFromMYSQL()
getCommentFromMYSQL()
print("Finish")
我发现问题是我的代码没有按顺序执行,getCommentFromMYSQL函数和getTopicIdFromMYSQL差不多,我想运行这三个按顺序执行怎么办?
代码总是按顺序执行。我认为你的问题是你在这一行中进行异步调用:
NSURLSession.sharedSession().dataTaskWithRequest(request)
但是,由于代码是按顺序执行的,因此在异步调用完成之前会调用方法 getCommentFromMYSQL()
。你应该在这个条件中调用 getCommentFromMYSQL()
:
if (resultValue == "Success") {
}
或者任何你想要的时候。这将确保在第一个方法完成执行后调用方法 getCommentFromMYSQL()
。
这是因为,您正在后台线程中进行异步调用,运行。
如果要顺序执行,分派到主队列后调用next方法,
dispatch_async(dispatch_get_main_queue(), {
//call here
getCommentFromMYSQL()
if(resultValue == "Success"){
}
else{
let error = UIAlertController(title: "Error", message: "Please check your network configuration!:-(", preferredStyle: .Alert)
let cancel = UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)
let ok = UIAlertAction(title: "OK", style: .Default, handler: nil)
error.addAction(cancel)
error.addAction(ok)
}
})
将完成处理程序作为参数添加到您的异步函数:
func getTopicIdFromMYSQL(completion: (AnyObject?, ErrorType?)->())
func getCommentFromMYSQL(completion: (AnyObject?, ErrorType?)->())
注: 完成处理程序 必须 在异步函数完成时最终被调用 - 要么出现错误,要么出现计算值。
然后调用这些函数,如下所示:
getTopicIdFromMYSQL() { (result1, error) in
if let result1 = result1 {
// process result1
// ...
getCommentFromMYSQL() { (result2, error) in
if let result2 = result2 {
// process result2
// ...
} else {
// handle error
}
}
} else {
// handle error
}
}
您可以按如下方式实现这些功能:
func getTopicIdFromMYSQL(completion: (AnyObject?, ErrorType?) {
let myUrl = NSURL(string: "xxxx")
let request = NSMutableURLRequest(URL: myUrl!)
request.HTTPMethod = "POST"
let email:String = "xxx@gmail.com"
let postString = "email=\(email)"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request){
data, response, error in
if error != nil {
completion(nil, error)
}
do {
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSDictionary
if let parseJSON = json {
let resultValue = parseJSON["status"] as? String
print("Get all topic")
favouriteTopic = parseJSON["getResult"]! as! [AnyObject]
completion(favouriteTopic, nil)
} else {
throw MyError.Error(message: "bogus JSON")
}
} catch let error {
completion(nil, error)
}
}
task.resume()
}