[英]Handling Scala Futures
我正在編寫Scala代碼,以檢查zip文件是否在Amazon S3上的某個位置可用。 如果是,我想返回路徑; 如果不是,我想創建它, 然后返回路徑。 答案是相同的(假設沒有例外)。
我正在將Rhinofly play-s3庫用於我的S3抽象,但是我認為這不太相關。 該庫確實使用了Scala Future
,這就是這里的重點。 我的問題是Scala不喜歡在開始不可用時創建zip的方法的返回類型。
這是我的代碼:
def zip(key: String): Future[String] = {
val zipFileName = key + ".zip"
val zipFile = bucket get zipFileName //Returns a Future[BucketFile] or S3Exception
zipFile.map(bucketFile => bucketFile.name).recover {
case S3Exception(status, code, message, originalXml) => createZip(key)
case _ => "Who cares for now?"
}
}
假設路徑愉快,並且唯一可能發生的異常是沒有現有zip的404。
同時, createZip(key)
返回Future[String]
我得到的編譯錯誤是這樣的:
type mismatch;
found : scala.concurrent.Future[String]
required: String
所以我想zip
方法返回Future[String]
。 我以為從zipFile
到bucketFile.name
的map
返回Future[String]
,而createZip
肯定返回Future[String]
。
所以有什么問題? 為什么String
是必需的返回類型? 如何重寫其中一個或兩個方法來實現我的目標?
recover
會將Future
恢復為默認值。 在這種情況下, String
。 你想要的是recoverWith
恢復Future
與另一個 Future
。
def zip(key: String): Future[String] = {
val zipFileName = key + ".zip"
val zipFile = bucket get zipFileName //Returns a Future[BucketFile] or S3Exception
zipFile.map(bucketFile => bucketFile.name).recoverWith {
case S3Exception(status, code, message, originalXml) => createZip(key)
}
}
您具有異步恢復(即,您的恢復返回的是Future[String]
而不是String
。請使用recoverWith
,它允許您使用創建Future
的回調。請注意,“誰在乎現在”需要升級為通過調用Future.success("Who cares for now")
Future
,否則您可以讓錯誤Future.success("Who cares for now")
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.