【问题标题】:How to implement asynchronous task in a function that must return some value?如何在必须返回某个值的函数中实现异步任务?
【发布时间】:2015-11-21 11:05:43
【问题描述】:

我正在使用异步操作(使用 parse SDK)。
我创建了一个这样的函数:

let result = try query.fromLocalDatastore().findObjects()
return result

问题是在控制台中我收到如下消息:

Warning: A long-running operation is being executed on the main thread. 
 Break on warnBlockingOperationOnMainThread() to debug.

我认为这是一个糟糕的设计,我正在为此寻找解决方案。
我将findObjects 更改为findObjectsWithBlock,但这是异步性质的问题,所以我永远不会从函数中得到结果(实际上它总是很晚:))。
我的问题是:

有没有办法运行此代码但避免在控制台中出现警告?

我是否正确,这是在函数中编写此代码的不好方法,另一种方法是在我调用函数的地方从函数编写代码,使其异步并失去代码重用的好处?

【问题讨论】:

    标签: swift asynchronous parse-platform


    【解决方案1】:

    尝试;

    let result = query.fromLocalDatastore().findObjectsInBackgroundWithBlock {
      (results: [PFObject]?, error: NSError?) -> Void in
      if error == nil {
        // results will contain users with a hometown team with a winning record
      }
    

    【讨论】:

    • 异步这实际上是问题所在。我调用函数let data = getSomeData(),但由于函数使用异步代码,它永远不会在我需要的地方返回值。所以data 将是nil 并且数据是在函数中获取的,但是晚了。
    猜你喜欢
    • 1970-01-01
    • 2017-12-16
    • 2019-01-30
    • 2019-04-25
    • 2023-01-20
    • 1970-01-01
    • 1970-01-01
    • 2021-04-06
    • 2013-03-22
    相关资源
    最近更新 更多