completion handler to finish tasks before running another

半世苍凉 提交于 2021-01-29 07:46:44

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!