calling asynchronous method inside for-loop [duplicate]

断了今生、忘了曾经 提交于 2019-12-23 03:15:52

问题


Trying to make my for loop behave synchronously when I am making an asynchronous call in each iteration of the loop. I have a feeling I will need to use Grand Central Dispatch in some way but not sure.

func test(strings: [String], completion: @escaping ((_ value: [String]) -> Void)) {
    var results: [String] = []
    for string in strings {
        Service.shared.fetch(with: string, completion: { (result) in
            results.append(result)
        })
    }
    // this will run before asynchronous method in for-loop runs n times.
    completion(results)
}

回答1:


You don't need to make this loop synchronous. What you really want is to call completion when you will get all results. You can use this solution (for free):

func test(strings: [String], completion: @escaping ((_ value: [String]) -> Void)) {
    var results: [String] = []  

    for string in strings {
        Service.shared.fetch(with: string, completion: { (result) in
            DispatchQueue.main.async { 
                results.append(result)
                if results.count >= strings.count {
                    completion(results)
                }
            }
        )
    }
}


来源:https://stackoverflow.com/questions/48254073/calling-asynchronous-method-inside-for-loop

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