DEV Community

Steve Voltmer
Steve Voltmer

Posted on

Waiting for async function before sending response

I am stuck with my first Node project. It is a Node server with one route (/data) to call the Eventbrite API for event data and then send the response back to the webpage. My webpage will be hosted on a different server than the Node project and I have a fetch request on the page to the route which then makes the Eventbright API call. Unfortunatly the response is still in a Promise state when the Node server sends back the response to the webpage. I've got everything in async functions, but it still isn't waiting. Here is my code.

// Node server getEvents is an async function that returns a response from the Eventbrite API.

const handleRequest = async (reqest, response) => {
    const data = await getEvents();
    if(reqest.url === 'http://127.0.0.1:3300/data'){
        response.setHeader('Content-Type', 'application/json');
        response.setHeader('Access-Control-Allow-Origin', '*');

        // End and send the response
        response.end(JSON.stringify(data));
    }

}
const server = http.createServer(handleRequest);

const port = 3300;
server.listen(port, () => {
    console.log(`Server running on port ${port}`);
});

// HTML webpage

<script type="text/javascript">
            async function eventsList() {
                try {
                    const response = await fetch('http://127.0.0.1:3300/data');
                    if(!response.ok) {
                        throw new Error('Network response was not ok');
                    }
                    const data = await response.json();
                    document.getElementById("events").textContent = data;
                } catch(error) {
                    console.log("Error:", error);
                }
            }
            eventsList()
    </script>
Enter fullscreen mode Exit fullscreen mode

Top comments (0)