仅在异步函数执行完毕后运行代码 [英] Run code only after asynchronous function finishes executing

查看:31
本文介绍了仅在异步函数执行完毕后运行代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

总体而言,我对 Swift 和 Xcode 还比较陌生,并且在试图弄清楚这一点时发现了很多困难.

I am relatively new to Swift and Xcode in general and am finding a lot of difficulty trying to figure this out.

我正在开发一个利用 Parse.com 后端服务器的应用程序.为了不阻塞主线程,每当应用程序从服务器下载任何内容时,它都会在不同的线程上异步完成.然而,其余代码继续在主线程上执行,当它应该从服务器获得的数据尚未下载时,它会崩溃.我想知道如何在异步函数完成后调用函数来运行,这必须为单独文件中的函数完成.

I am developing an app that utilizes the Parse.com backend server. In order not to block the main thread, whenever the app downloads anything from the server, it is done on a different thread, asynchronously. However the rest of the code continues to execute on the main thread, and it crashes when the data it is supposed to have from the server has not downloaded yet. I would like to know how to call functions to run after the asynchronous function finishes, and this has to be done for functions in separate files.

我读到闭包可能对此有所帮助,但我发现语法非常困难,非常感谢您的解释.但是任何方式都会很有帮助.

I read that closures might help with this, but I found there syntax very difficult and an explanation would be greatly appreciated. But any way would be very helpful.

谢谢

推荐答案

好吧,你只需在异步回调的末尾调用函数.那是异步回调结束的时候 - 这是异步回调中的其他所有内容都完成的时候!所以,例如:

Well, you simply call the function at the end of the asynchronous callback. That is when the asynchronous callback has ended - it is when everything else in the asynchronous callback has finished! So, for example:

func myMethod() {
    // ... code ...
    somebody.doSomethingWith(someObject, asynchronousCallback: {
        (thing, otherThing) in
        // ... do whatever
        // --> CALL THE FUNCTION!
    })
    // ... code ...
}

如果问题是你不知道调用什么函数,你可以配置你周围的函数/对象,以便有人可以递给你一个函数,然后你在上面我说调用函数"的地方叫什么.

If the problem is that you do not know what function to call, you can configure your surrounding function / object so that someone can hand you a function which is then what you call in the spot where I said "call the function" in the above.

例如:

func myMethod(f:() -> ()) { // we receive the function as parameter
    // ... code ...
    somebody.doSomethingWith(someObject, asynchronousCallback: {
        (thing, otherThing) in
        // ... do whatever
        // --> CALL THE FUNCTION, by saying:
        f()
    })
    // ... code ...
}

这篇关于仅在异步函数执行完毕后运行代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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