如何知道两个异步功能何时完成? [英] How to know when two async functions have finished?

查看:74
本文介绍了如何知道两个异步功能何时完成?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 func load(completionHandler:(someVar1 : SomeType, someVar2 : SomeType)-> Void){ 
   asyncFunc1() {
   (someVar1) -> Void in
   }
   asyncFunc2() {
   (someVar2) -> Void in
   }
}

这两个函数如何沟通完成了吗?我希望能够编写我的加载函数的completeHandler的代码,以便在asyncFunc1和asyncFunc2均完成时执行,然后返回someVar1和someVar2。

How would one go about communicating when both functions have completed? Id like to be able to code my load function's completionHandler to execute when BOTH asyncFunc1 and asyncFunc2 are completed to then return both someVar1 and someVar2.

推荐答案

您可以使用计数器来知道两种方法何时完成执行。拥有一个计数器具有更高的可伸缩性,因为它实际上允许使用许多异步方法:

You can use a counter to know when both methods finished executing. Having a counter is more scalable, as it allows for virtually any number of async methods:

func load(completionHandler:(someVar1 : SomeType, someVar2 : SomeType) -> Void){ 
    var callbacksLeft = 2
    let completionCallback = {
        print("All calls completed, let's do some work")
    }
    func checkCompleted() {
        callbacksLeft -= 1
        if callbacksLeft == 0 {
            completionCallback()
        }
    }

    asyncFunc1() { someVar1 in
        checkCompleted()
    }
    asyncFunc2() { someVar2 in
        checkCompleted()
    }
}

或者,如果可以用相同的方式调用函数,例如两者都没有参数,或者具有相同的参数列表,您可以通过使用数组来缩短代码(这也较不易出错,因为在第一个实现中,如果添加新功能,则必须在两个位置更新代码-更新 callbacksLeft 值,并添加实际的函数调用):

Or, if the functions can be called the same way, e.g. both have no params, or have the same parameters list, you can shorten the code by using an array (this also less error-prone as in the first implementation you'd have to update the code in two places if you add a new function - update the callbacksLeft value, and add the actual function call):

func load(completionHandler:(someVar1 : SomeType, someVar2 : SomeType) -> Void){ 
    let funcsToCall = [asyncFunc1, asyncFunc2]
    var callbacksLeft = funcsToCall.count
    let completionCallback = {
        print("All calls completed, let's do some work")
    }

    for funcToCall in funcsToCall {
        funcToCall {
            callbacksLeft -= 1
            if callbacksLeft == 0 {
                completionCallback()
            }
        }
    }
}

即使函数的调用方式不同,也可以将它们包装在闭包中:

And even if the functions are not called the same way, you can wrap them in closures:

let funcWrapper1 = { (callback: () -> Void)
    return asyncFunc1(argumentsForFuc1, callback)
}
let funcWrapper2 = { (callback: () -> Void)
    return asyncFunc2(argumentsForFunc2, callback)
}
let funcsToCall = [funcWrapper1, funcWrapper2]

这篇关于如何知道两个异步功能何时完成?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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