Server Side Swift with Vapor · Async | raywenderlich.com


This is a companion discussion topic for the original entry at https://www.raywenderlich.com/870225-server-side-swift-with-vapor/lessons/8

How to get the async project example from this lecture to see how it works?

Hi @yauheni - the code wasn’t uploaded because it was all dummy code just to demonstrate how it works (and didn’t actually do anything). The best place to look for examples that actually do some work is probably GitHub - raywenderlich/vapor-til: The TIL Application for the Vapor book

Let me know if you have any other questions!

Hi @0xtim. Thanks for the reply. I did se the example, also I’ve read the book. But didn’t get how to use futures and promises. The problem is that in you examples you don’t create future or promise. Instead you use API of other classes that already have future. But to understand, I want to see the hole life circle of future and promise. From creating, async working, pass it through as parameter, till deleting from memory.
Thanks in advance, Yauheni.
indent preformatted text by 4 spaces
static func start<T:Content> (request: RestRequest, completion: ((_ response: T)->())?) {

guard let ws = try? HTTPClient.webSocket(scheme: .wss, hostname: request.hostName, port: request.port, path: request.path, on: wsClientWorker).wait() else {
  print("Ws \(request.hostName) is nil")
  return
}

ws.onText { ws, text in
  //      print(text)
  if let jsonData = text.data(using: .utf8), let response: T = try? JSONDecoder().decode(T.self, from: jsonData) {
    completion?(response)
  } else {
    print("Error with parsing \(T.self) ws response:", text)
    return
  }
  
}

}Preformatted text

So the docs (https://docs.vapor.codes/3.0/async/overview/#promise) are probably the best place to get started to see how to use promises etc. Also the Vapor source code is a good place to look through. What are you trying to do with the code block?

Yep, looked the docs, but probably I’m not so good to get it. Not enough examples for me(

The goal was to create ws conections with difrent parameters to able to send messages to it and get messages from it.
What I didn’t liked in that example - is “wait”, becase I have a lot of ws connections to different servers.
I’ve solve this in such way:
class BitstampWs: BaseWs {

  var tickerResponse: ((_ response: BitstampTickerResponse)->())?
  
  func startListenTickers(forPairs: [BitstampPair]) {
        
    let _ = HTTPClient.webSocket(scheme: .wss, hostname: "ws.bitstamp.net", on: wsClientWorker).do { (ws) in
      
      for pair in forPairs {
        let bookRequest: [String : Any] = ["event":"bts:subscribe", "data":["channel": "live_trades_\(pair.urlSymbol)"]]
        guard let bookRequestJsonData = try?  JSONSerialization.data(
          withJSONObject: bookRequest,
          options: []
          ) else {
            print("can't parse bitstamp json:", pair)
            return
        }
        self.ws = ws
        ws.send(bookRequestJsonData)
      }
      
      ws.onText { ws, text in
        guard  let jsonData = text.data(using: .utf8) else {
          print("Error with parsing bitstamp ws response")
          return
        }
        if let tickerResponse: BitstampTickerResponse = try? JSONDecoder().decode(BitstampTickerResponse.self, from: jsonData) {
          self.tickerResponse?(tickerResponse)
        } else if let _: BitstampInfoResponse = try? JSONDecoder().decode(BitstampInfoResponse.self, from: jsonData)  {
          //do nothing for now
        }
        else {
          print("Error with parsing bitstamp ws response")
          return
        }
      }
      
    }
    
    
    
  }
  
}

And do create such class for each ws server configuration.

If you have any suggestion how to do it in more correct way, please help. I specially for that bought the book and subscribed for the course.

Also not sure about worker. I’ve just created global
let wsClientWorker = MultiThreadedEventLoopGroup(numberOfThreads: 1)
and using it for each ws connection for diff servers. Is it correct of from where should I take worker?

@0xtim Can you please help with this when you get a chance? Thank you - much appreciated! :]

Ahh ok, you’re using web sockets. So unfortunately things get a little complicated because the WS API doesn’t account for futures particularly well. One option is to use GCD (and then you can use wait()). If you’re still struggling, best option is to jump on to the Vapor Discord and ask there, I think a couple of people have done this kind of thing.

I was understanding everything until i came to these codes :cry:

@giulianoaccorsi what specifically are you stuck on. There’s more docs on Vapor’s documentation page that may help and to be honest the best way to learn is to just get stuck in and start seeing how you deal with futures in the rest of the book.