How to implement long polling with JavaScript async functions?

Content verified by Anycode AI
July 21, 2024
Long polling is a Web-based communication technique that allows real-time updates from the server to the client. Unlike normal polling, which sends new requests at fixed intervals, long polling keeps the request open until new data is ready to be sent. In this way, it avoids expending many resources on the server and network traffic for no reason at all; therefore, the approach is appropriate for chat systems, notifications, and real-time monitoring dashboards. This guide shows realization of long polling with JavaScript async functions and explains in detail how a responsive web client and a Node.js server can be developed that efficiently handles long-polling requests.

Long polling is pretty cool, really. It lets web apps feel a bit more like they're in real-time. The way it works is quite simple: the client makes a request to the server and the server keeps the connection open until there's new data. Once the client gets the data, it makes a new request immediately, and this cycle goes on, making sure your app gets a steady stream of updates. Super useful for things like chat applications and live notifications!

Setting Up the Server

First thing’s first, let's set up the server. We'll do this using Node.js and the Express framework.

Install Node.js and npm if you haven’t yet.

Create a new directory for your project and hop into it.

Run npm init -y to set up a new Node.js project.

Install Express by running npm install express.

Now, create a file named server.js and add the following code:

const express = require('express');
const app = express();
const PORT = 3000;

let latestData = null;

app.use(express.json());

app.get('/poll', (req, res) => {
    const checkForData = () => {
        if (latestData) {
            res.json({ data: latestData });
            latestData = null; 
        } else {
            setTimeout(checkForData, 1000); 
        }
    };
    checkForData();
});

app.post('/data', (req, res) => {
    latestData = req.body.data;
    res.status(201).send('Data received');
});

app.listen(PORT, () => {
    console.log(`Server running on port ${PORT}`);
});

Here's what’s happening:

  • The /poll endpoint continuously checks if there's new data every second. When there is data, it sends it back to the client.
  • The /data endpoint lets us simulate new data being sent to the server.

Setting Up the Client Side

Now, let's set up the client side. Create an HTML file named index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Long Polling Example</title>
</head>
<body>
    <h1>Long Polling Example</h1>
    <div id="dataDisplay">Waiting for data...</div>

    <script>
        async function longPoll() {
            try {
                const response = await fetch('/poll');
                if (!response.ok) {
                    throw new Error(`Error: ${response.status}`);
                }
                const result = await response.json();
                document.getElementById('dataDisplay').innerText = `Data: ${result.data}`;
            } catch (error) {
                console.error('Polling error:', error);
                await new Promise(resolve => setTimeout(resolve, 5000)); 
            } finally {
                longPoll();
            }
        }

        longPoll(); 
    </script>
</body>
</html>

Here's the breakdown:

  • The longPoll function is defined asynchronously.
  • Inside this function, we make a fetch call to the /poll endpoint.
  • If there's an error, we catch it and log it, and then wait for 5 seconds before retrying.
  • If successful, it displays the data and calls itself again to continue polling.

Running the Application

Start your server by running node server.js.

Open your index.html in a web browser.

The page will keep polling the server and update the displayed data as new data comes in.

Testing the Setup

To see it in action, you can simulate new data by sending a POST request to the /data endpoint. You can use tools like Postman or cURL:

curl -X POST \
     -H "Content-Type: application/json" \
     -d '{"data": "This is new data"}' \
     http://localhost:3000/data

When you do this, the new data should appear on your web page promptly.

Summary

So, that's how you can set up long polling with JavaScript async functions! The client makes repeated requests to the server, which only responds when there's new data. This setup helps your web app stay updated in real-time without making unnecessary network requests continuously. Plus, it’s kinda fun to set up something that feels so immediate and responsive!

Have any questions?
Our CEO and CTO are happy to
answer them personally.
Get Beta Access
Anubis Watal
CTO at Anycode
Alex Hudym
CEO at Anycode