本文介绍了如何快速从异步块返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请查看下面的代码:

backgroundthread.async {
    return self.mycallback() //return string, int etc
}

我想从异步块返回一个值.我不需要任何完成处理程序或任何其他解决方法.

I want to return a value from an async block. I don't want any completion handler or any other workaround.

func getAppConfigFromDB(_ key: String) -> String
{
   let value = String()
   backgroundthread.async {
      let inst = AppConfigDB.init(_APP_CONFIG_DB_PATH)
      value = inst.getConfigurationInfo(key) // I want to return from here.
   }
   return value
}


getAppConfigFromDB("path")

推荐答案

就像@rmaddy所说的那样,除了使用完成处理程序之外,您别无选择.

Like @rmaddy said, you have no other way than to use completion handlers.

func getAppConfigFromDB(_ key: String, completion: @escaping ((String) -> Any)) {
    let value = String()
    backgroundthread.async {
        let inst = AppConfigDB.init(_APP_CONFIG_DB_PATH)
        value = inst.getConfigurationInfo(key) // I want to return from here.
        completion(value)
    }
}

您这样调用方法.

getAppConfigFromDB("") { (value) -> Any in
    // Use value to do something
}

这篇关于如何快速从异步块返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-03 17:44