How to wait for a WebSocket's readyState to change

后端 未结 9 2334
梦如初夏
梦如初夏 2020-11-30 00:54

I\'m trying to implement a WebSocket with a fallback to polling. If the WebSocket connection succeeds, readyState becomes 1, but if it fails, readyState

9条回答
  •  旧巷少年郎
    2020-11-30 01:07

    If you use async/await and you just want to wait until the connection is available I would suggest this function :

    async connection (socket, timeout = 10000) {
      const isOpened = () => (socket.readyState === WebSocket.OPEN)
    
      if (socket.readyState !== WebSocket.CONNECTING) {
        return isOpened()
      }
      else {
        const intrasleep = 100
        const ttl = timeout / intrasleep // time to loop
        let loop = 0
        while (socket.readyState === WebSocket.CONNECTING && loop < ttl) {
          await new Promise(resolve => setTimeout(resolve, intrasleep))
          loop++
        }
        return isOpened()
      }
    }
    

    Usage (in async function) :

    const websocket = new WebSocket('...')
    const opened = await connection(websocket)
    if (opened) {
      websocket.send('hello')
    }
    else {
      console.log("the socket is closed OR couldn't have the socket in time, program crashed");
      return
    }
    

提交回复
热议问题