如何在Promisekit循环中使用when函数

时间:2018-05-31 18:41:26

标签: swift loops promisekit

我有一系列约会,我正试图从我们的windows azure blob存储中获取这些约会的所有照片。首先,我想获得具有关联的appointmentId的blob列表,以便我可以在之后正确下载和存储它们。

我正在使用PromiseKit,但我不确定如何在循环中使用PromiseKit:

for appointment in appointments {
  // Get blobs
}

到目前为止,这是我的代码。非常感谢任何帮助!

func getBlobsPromise(appointmentId: Int32) -> Promise<[BlobDownload]>  {
return Promise { seal in
    var error: NSError?
    var blobDownloads = [BlobDownload]()
    container = AZSCloudBlobContainer(url: URL(string: containerURL)!, error: &error)
    if ((error) != nil) {
        print("Error in creating blob container object. Error code = %ld, error domain = %@, error userinfo = %@", error!.code, error!.domain, error!.userInfo)
        seal.reject(error!)
    }

    let prefix: String = "AppointmentFiles/\(appointmentId)"

    container?.listBlobsSegmented(with: nil, prefix: prefix, useFlatBlobListing: true, blobListingDetails: AZSBlobListingDetails(), maxResults: 150) { (error : Error?, results : AZSBlobResultSegment?) -> Void in

        if error != nil {
            seal.reject(error!)
        }

        for blob in results!.blobs!
        {
            let blobInfo = blob as! AZSCloudBlob
            if blobInfo.blobName.lowercased().contains("jpg") || blobInfo.blobName.lowercased().contains("jpeg") {
                let blobDownload: BlobDownload = BlobDownload(appointmentId: Int(jobId), blob: blobInfo)
                blobDownloads.append(blobDownload)
            }

        }

        seal.fulfill(blobDownloads)
    }
}

}

按预期返回blob,但我希望在继续之前获取所有约会的所有blob。这是我尝试过的(除其他外):

func getBlobsForAllJobs(appointmentIds: [Int32]) -> Promise<[BlobDownload]> {
return Promise { seal in
    let count = appointmentIds.count - 1
    let promises = (0..<count).map { index -> Promise<[BlobDownload]> in
        return getBlobsPromise(agencyCode: agencyCode, appointmentId: appointmentIds[index])
    }
    when(fulfilled: promises).then({ blobDownloads in
        seal.fulfill(blobDownloads)
    })
}

}

编辑1

我使用DispatchGroup和完成处理程序解决了这个问题。这是代码,以防有人感兴趣。如果有替代(更好)的方式,我很乐意听到他们。我是一名刚进入斯威夫特的人。

func getBlobsToDownload(appointmentIds: [Int32], completion: @escaping ([BlobDownload]) -> Void) {
var myBlobsToDownload = [BlobDownload]()
let myGroup = DispatchGroup()

for apptId in appointmentIds {
    myGroup.enter()

    getBlobs(appointmentId: apptId) { (blobDownloads) in
        print("Finished request \(apptId)")
        print("Blobs fetched from apptId \(apptId)  is \(blobDownloads.count)")
        for blobDownload in blobDownloads {
            myBlobsToDownload.append(blobDownload)
        }
        myGroup.leave()
    }
}

myGroup.notify(queue: .main) {
    print("Finished all requests.")
    completion(myBlobsToDownload)
}

}

0 个答案:

没有答案
相关问题