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

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

问题描述

总的来说,我对 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天全站免登陆