问题
I'm really tying myself up in a knot here getting very confused with how to perform tasks in the order i want them to happen.
i have function to build an array from server data and return a result which is the array. - this works fine and does return the result.
upon the completion of this happening (twice) i want to run another function. for some reason at the moment i am trying to embed these functions in another function with a completion block that will return true once these 2 have completed and returned data, but the way I'm trying this its returning the result before the function has completed.
func getCollectionArrays(_ block: ((Bool) -> Void)? = nil) {
var resultPack: Bool!
var resultPart: Bool!
BuildArray.buildArrayFromQuery(queryForCollection: "Pack", sender: self, completeBlock: { (result) in
if result != nil {
resultPack = true
}
})
BuildArray.buildArrayFromQuery(queryForCollection: "Part", sender: self, completeBlock: { (result) in
if result != nil {
resultPart = true
}
})
// this is returning nil because there isn't enough time for "BuildArray.buildArrayFromQuery" to run
if resultPack == true && resultPart == true {
block!(true)
}
}
回答1:
Move the next step into the preceding closure. Keep nesting. Like so:
func getCollectionArrays(_ block: ((Bool) -> Void)? = nil) {
var resultPack: Bool!
var resultPart: Bool!
BuildArray.buildArrayFromQuery(queryForCollection: "Pack", sender: self, completeBlock: { (result) in
if result != nil {
resultPack = true
}
// next step, nested in this closure
BuildArray.buildArrayFromQuery(queryForCollection: "Part", sender: self, completeBlock: { (result) in
if result != nil {
resultPart = true
}
// next step, nested in _this_ closure
if resultPack == true && resultPart == true {
block!(true)
}
})
})
}
来源:https://stackoverflow.com/questions/41476314/completion-handler-to-finish-tasks-before-running-another