1

I am trying to use async await / Promise. I have a function like this:

extension DemoWebCrypto {

    class func runWEC(password: String, encrypted: Data) {
        let crypto = WebCrypto()
        crypto.decrypt(data: encrypted,
                       password: password,
                       callback: { (decrypted: Data?, error: Error?) in
              print("Error:", error)
              let text = String(data: decrypted!, encoding: .utf8)
              print("decrypt:", text)
        })
    }

}

Normally we call this function like this

let enc1 = "......."
let password = "....."
let data1 = Data(base64Encoded: enc1, options: .ignoreUnknownCharacters)!
DemoWebCrypto.runEC(password: password, encrypted: data1) {

}

So I want to remove this trailing closure implementation via AwaitKit i.e. want to replace via async await way.

How I do that so I can get the string? Something like

let result = try await(DemoWebCrypto.runWEC(password: ..., encrypted: ...))
print(result) // the decrypt text
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Abhishek Thapliyal
  • 3,497
  • 6
  • 30
  • 69

1 Answers1

0

AwaitKit works in conjunction with PromiseKit to get the result you're waiting for. You'll need to change your function runWEC to return a Promise of a String like so:

class func runWEC(password: String, encrypted: Data) -> Promise<String> {
    return Promise { seal in
        let crypto = WebCrypto()
        crypto.decrypt(data: encrypted,
                       password: password,
                       callback: { (decrypted: Data?, error: Error?) in
              if let error = error {
                  seal.reject(error)
              }

              let text = String(data: decrypted!, encoding: .utf8)
              seal.fulfill(text)
        })
    }
}

Then you'll be able to use the try? await() function.

if let result = try? await(DemoWebCrypto.runWEC(password: ..., encrypted: ...)) {
    print(result) // the decrypt text
}
user2759839
  • 305
  • 1
  • 3
  • 11