我主要使用Scala和JavaScript等编程语言.我试图理解在两种语言中如何使用异步响应式编程的相似点和不同点.你能帮助我吗?
我没有采用任何特定的Js Promise框架,因为它似乎很多实现了类似的规范(如Promise/A).到目前为止我只使用过Q.
似乎在Javascript中我们称之为Deferred我们解决的对象来完成一个Promise.在Scala中,似乎Promise是你决定获得Futuremonad 的对象.
有人可以告诉我这是对的吗?Promise在Js和Scala之间使用不同术语有什么好的理由吗?
此外,在Scala中,我们通常Future使用像(map和Haskell)这样的运算符进行进一步计算来链接monad .在Js中这些相当于什么?flatMapbind
我可能是错的,但在我看来,在JS中的then一个Promise种类同时处理的map和flatMap运营商吗?如果是这样,是否有可能获得一个promise of promise of resultin Js?就像我们可以Future[Future[Result]]在Scala中获得一个(Future[Result]无论如何都可以扁平化).
Js Promise是monad吗?即使方法名称与我们在monad文献中找到的名称不匹配,它似乎也是如此.
错误Reference to generic type Dictionary requires arguments in <...>出现在函数的第一行.我试图让函数返回从api检索到的NSDictionary.有谁知道这里会发生什么?
class func getCurrentWeather(longitude: Float, latitude: Float)->Dictionary?{
let baseURL = NSURL(string: "https://api.forecast.io/forecast/\(apikey)/")
let forecastURL = NSURL(string: "\(longitude),\(latitude)", relativeToURL:baseURL)
let sharedSession = NSURLSession.sharedSession()
let downloadTask: NSURLSessionDownloadTask = sharedSession.downloadTaskWithURL(forecastURL!, completionHandler: { (location: NSURL!, response: NSURLResponse!, error: NSError!) -> Void in
if(error == nil) {
println(location)
let dataObject = NSData(contentsOfURL:location!)
let weatherDictionary: NSDictionary = NSJSONSerialization.JSONObjectWithData(dataObject!, options: nil, error: nil) as NSDictionary
return weatherDictionary
}else{
println("error!")
return nil
}
})
}
Run Code Online (Sandbox Code Playgroud)
编辑:
第二期:
class …Run Code Online (Sandbox Code Playgroud) 我不想检查我的url statusCode是否等于200,如果statusCode等于200,我创建了一个返回布尔函数的函数,我正在使用dataTask,但我不知道如何返回一个值:
class func checkUrl(urlString: String) -> Bool{
let urlPath: String = urlString
var url: NSURL = NSURL(string: urlPath)!
var request: NSURLRequest = NSURLRequest(url: url as URL)
var response: URLResponse?
let session = Foundation.URLSession.shared
var task = session.dataTask(with: request as URLRequest, completionHandler: {(data, response, error) in
if let error = error {
print(error)
}
if let data = data{
print("data =\(data)")
}
if let response = response {
print("url = \(response.url!)")
print("response = \(response)")
let httpResponse = response as! HTTPURLResponse …Run Code Online (Sandbox Code Playgroud) 我有一个函数让我们称之为"a"运行一些代码然后返回一个字符串"x"在异步代码块中更新然后返回.
在异步代码运行之后,我将如何让程序等待返回x?
func a() -> String {
//code
//code
var x: String
async block {
x = "test"
}
return x
}
Run Code Online (Sandbox Code Playgroud) 请查看以下代码:
backgroundthread.async {
return self.mycallback() //return string, int etc
}
Run Code Online (Sandbox Code Playgroud)
我想从异步块返回一个值。我不想要任何完成处理程序或任何其他解决方法。
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")
Run Code Online (Sandbox Code Playgroud) 我是 Swift 的新手,我正在尝试返回在此函数中创建的变量的值。我已经面临这个问题很长一段时间了,希望任何人都可以对此有所了解并帮助我。我曾尝试更改函数的返回类型,但没有奏效。任何帮助将不胜感激
这是代码:
func grabData1() -> (String, String, String) {
db.collection("News").document("Article 1").getDocument { (document, error) in
if error == nil {
if document != nil && document!.exists{
self.headline1 = document?.get("Headline").map(String.init(describing:)) ?? nil
var article = document?.get("Article").map(String.init(describing:)) ?? nil
var image1URL = URL(string: document?.get("Image") as! String)
return (headline1, article, image1URL)
}
}
}
}
Run Code Online (Sandbox Code Playgroud) 我试图在执行未立即完成的函数后从函数返回一个值。
例如:
func returnSomeValue() -> String {
let group = DispatchGroup()
group.enter()
service.longTimeTofinish(onFinish: { group.leave() } ) // <-- this function takes long time to finish
group.notify(queue: .main) {
return "Returning some value as example" // <-- Here is the issue
}
}
Run Code Online (Sandbox Code Playgroud)
编译器显示错误“无法将类型‘String’的值转换为闭包结果类型 Void”。通知内部的闭包无法将值返回给我的外部函数。有什么想法如何解决这个问题吗?
我正在使用 Swift 5、SwiftUI 和 Firebase 进行一个简单的项目,该项目循环遍历数组中的给定 id,在 Cloud Firestore 数据库中搜索每个 id,并将与该 id 关联的相应名称附加到新数组中。
例如,我得到一个数组的几个 id,然后对于给定数组中的每个元素,我获取与该 id 关联的文档,然后打印该文档中的“firstname”字段。
但是,我想将检索到的每个“名字”值存储到本地的单独数组中以备后用。在 Javascript 中,我知道这是使用 await 和 async 函数完成的,但是我在无数小时的故障排除中发现 Swift 没有 async 或 await。
这是我的代码:
func convertToNames(arr: [String]) -> [String]{
var newArr : [String] = []
for id in arr {
let docRef = db.collection("users").document(id)
docRef.getDocument { (document, error) in
if let document = document, document.exists {
let dataDescription = document.data().map(String.init(describing:)) ?? "nil"
let data = document.get("firstname") ?? "nil"
print("gotten data: \(data)")
newArr.append(String(describing: …Run Code Online (Sandbox Code Playgroud) swift ×7
firebase ×2
ios ×2
asynchronous ×1
deferred ×1
dictionary ×1
future ×1
iphone ×1
javascript ×1
nsurlrequest ×1
promise ×1
scala ×1
swift3 ×1
xcode ×1