Synchronicity

Learn to use asynchronous calls with Transcrypt.

Introducing synchronicity

Now that we have a proxy server to host our back-end and front-end web servers, let’s talk about how we get data into our front-end application from our back-end server.

A good user experience is key to a successful application in front-end web development. The last thing we want to do is display a loading icon while our application sends a query to the back-end web server to pull in data. For this reason, synchronous web service calls have become outdated in favor of asynchronous calls. This results in our application not going into a holding pattern while waiting for data to arrive. Instead, it continues to be responsive to the user’s actions. When the data we requested arrives from the back-end server, our application processes it at that point asynchronously.

As a Python developer, our first instinct for making HTTP requests might be to import the urllib module or the Python requests library, but they won’t work with Transcrypt. Fortunately, they are not needed. There are existing JavaScript libraries available that we can utilize in our front-end web applications that can handle the asynchronous communication tasks for us. Here, we’ll focus on the window.fetch() method that is built-in to JavaScript.

JavaScript’s fetch function

The fetch() method takes a URL string as a parameter and returns a promise in its simplest form. The promise object that is returned from the fetch() method is a placeholder in our code for an asynchronous function call. When the response is received back from the server, the status of the promise object is updated, and it will call a function we provide to process the returned data. If there is an error during the fetch() call, it will call another function that we provide for handling errors. The callback functions that are provided to fetch() and the order they are processed is referred to as the promise chain. To simplify the fetch() method, let’s wrap it in a Python convenience function that will make it easier ...