DEV Community

Jack 'eXit' Whitter-Jones
Jack 'eXit' Whitter-Jones

Posted on

Week 5 - Promises, promises, promises

API communication is the pivotal point in how websites communicate between each other and this is where JavaScript shines. This blog post delves into how JavaScript works through the use of Promises, and Fetch.

The main resources used are:

What Was Learnt

Promises have been the main stay of my weeks revision, along with the fetch function.

Promises provide the functionality to achieve asynchronous communication between clients and servers. When a client and server talk, the communication stream can take a period of time to respond. With this being the case, synchronous communication begins to fall down as it blocks or in other words freeze the application.

Asynchronous programming enables applications to be non-blocking, that allows the application to continue processing, but also allows for communicating between a client and server in the background. Promises are the key to making this work.

Promises object within JavaScript allows communications between client and servers to share data between one another. A client connects to a server through a URL. The server returns a promise, ensuring that the client and server share communication stream but allow for a period of time for data to be sent. The following code example demonstrates how an API function might return a Promise when it has been contacted by a client:

function getMyAPI(ip){
    return new Promise((resolve, reject) => {
           if(ip === "127.0.0.1"){
                reject("No local host addresses please...");
           }
           resolve({
                msg: "Yay you got my message...";
           });
    })
}
Enter fullscreen mode Exit fullscreen mode

The outcome of this code example can be split into three stages:

  • Pending - The state that is used when communication is being conducted
  • Fulfilled - When the communication is complete, even if there is a 404
  • Rejected - Communication has been failed, perhaps through network issues

The resolve function provides a fulfilled state to the promise, this is where data is typically sent back in JSON format.

The reject function provides an error for the communication stream so that developers can handle the outcome.

By now, this should remind you of another type of functionality, the try-catch structure.

try {
   // handle success
} catch {
   // handle error
}
Enter fullscreen mode Exit fullscreen mode

To handle the promise that an API returns, we can use the follow code example:

    fetch("fakeSite").then(response => response.json()).then(data => console.log(data)).catch(error => console.log(error));
Enter fullscreen mode Exit fullscreen mode

In this example, a promise is returned by the fetch function, which is handle by the then function. This handles the response from the API. The .json() part of the function itself returns another promise, which we can use the .then function again to handle the data. Finally, the .catch handles any errors asynchronously preventing the application from blocking.

Finally, to handle the data of the second then we should consider passing the data to a function, in this case we have used console.log but we can send it to a database for example. The reason we do this, is because the data does not live outside the scope of the then function.

One of the key findings of this weeks learning has been the interaction of asynchronous coding style. One key importance of using async code is to ensure that all code is asynchronous throughout the life span of that function. If not, the application will become blocking, and slow down the speed and performance of the application.

Resource Review

LearnJavaScript has been an excellent resource for learning this important concept. LearnJavaScript has been able to explain the concept through step-by-step approach that builds each lesson. One of the most important concept for learning promises has been the comparison to try catch structure. A typically hard concept for many, LearnJavaScripts step-by-step breakdown of the concept in suitable components.

Retrospective

The promise and fetch execution has been an interesting topic. For learning this functionality, it is worth building fake API functionality, or even to interlinking with third-party APIs to get a wider understanding of the process. Additionally, it is also quite fun to capture the traffic within Wireshark to understand the networking side of HTTP.

Over the next week I will try to apply third-party interaction to compound the learning that has been done so far.

Sign Off

It has been a turning point over the course of the week and has highlighted how proficient JavaScript can be.

Until next week!

Jack/eXit

Discussion (0)