DEV Community

mixbo
mixbo

Posted on

Handwriting long polling

Alt Text

Generally speaking we should use long connect in some real time communication scenes like: chat, web game etc.

WebScoket is useful tech to implement real time communication also Server Side Events is.

How to implement long polling manual? let's begin

The flow:

  1. A request is sent to the server.
  2. The server doesnโ€™t close the connection until it has a message to send.
  3. When a message appears โ€“ the server responds to the request with it.
  4. The browser makes a new request immediately.

The code:

async function subscribe() {
  let response = await fetch("/subscribe");
  if (response.status == 502) {
    await subscribe();
  } else if (response.status != 200) {
    notify(response.statusText);
    await new Promise(resolve => setTimeout(resolve, 1000));
    await subscribe();
  } else {
    let message = await response.text();
    notify(message);
    await subscribe();
  }
}
subscribe();
Enter fullscreen mode Exit fullscreen mode

subscribe will await request response

If response 502 maybe network error will try call subscribe again.

If response not ok(response status not equal 200) will notify error message and after one second try call subscribe again.

Else if response ok notify response body and immediately call subscribe again

Simply say subscribe function makes a fetch, then waits for the response, handles it and calls itself again.

Hope it can help you :)

Top comments (0)