在for循环中调用异步方法 [英] calling asynchronous method inside for-loop

查看:132
本文介绍了在for循环中调用异步方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在循环的每个迭代中进行异步调用时,尝试使我的for循环行为同步.我觉得我需要以某种方式使用Grand Central Dispatch,但不确定.

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)
}

推荐答案

您无需使该循环同步.您真正想要的是在获得所有results时调用completion.您可以免费使用此解决方案:

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)
                }
            }
        )
    }
}

这篇关于在for循环中调用异步方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆