Dead in The Water: Async Behavior
Type Your Shark Level 1

Dead in The Water: Async Behavior

During the 15 week program at the Flatiron School Software Engineering bootcamp, students are expected to produce five projects. Some of these are paired programming assignments, while the others are self-paced. Module three marks the first stand alone project with minimal requirements: Vanilla JavaScript Front, Ruby on Rails Back, Full Authentication, and Full-CRUD. With that in mind, I created Type Your Shark.

Despite many challenges, this low-level game taught me how to be a better JavaScript programmer. This post will be part 1 in a 3 part series that covers the most challenging road-blocks I encountered and how I manipulated JavaScript to overcome them. First up, is asynchronous behavior. Manipulating async functions in one way or another aids in persisting data throughout the game or on page reload.

Asynchronous Behavior

JavaScript runs top-down, meaning variables must be declared before they are used, and the timing of events and their location on the page can drastically effect the way the program runs. In my case, this led to strange behavior of the sharks or the authentication. Sometimes, it was as simple as moving a line of code up, and sometimes it required total restructuring.

JavaScript has a few tools to assist in dealing with asynchronous behavior, notably async and await functions. The idea here, is to make the entire function declaration async and place an await keyword in front of the code block you need to happen first. This makes all the subsequent code wait until the specified code has been run. Below is an example I used in conjunction with an event listener.

 document.querySelectorAll(".deleteButton").forEach(game => {

        game.addEventListener("click", async (event) => {
            event.target.parentNode.remove()
            await fetch(`https://localhost:3000/games/${event.target.id}`, {
                method: 'DELETE'
            })

            fetch(`https://localhost:3000/users/${currentUserId}`)
                .then(response => response.json())
                .then(redefineStats)
        })
    })

In the code above, I needed an event listener on the delete button associated with each game instance belonging to a user. I wanted to have the ability to delete the game instance and have the users stats update optimistically and pessimistically with that change. In order to do this, I made the event listener an async function with an await on my delete action. The delete needed to finish before I could update the users stats, or the stats wouldn't reflect the loss from deleting a game. This logic was used several times throughout the game, on nearly every network request.

The example code also shows another JavaScript asynchronous tool. Using a fetch with .then statements can help guide the flow of the program. By that I mean, let the network request to the endpoint happen, then take the returned response, and do something with that. That action can mean setting a variable with the response, or calling a function that now has access to the response.

The last tool I used to combat the timing bugs, was DOMContentLoaded. Before the page even loaded for the user to see, I needed to check local storage for a token to authenticate them. Based on whether the token existed or not, a few different things need to load or append.

document.addEventListener('DOMContentLoaded', () => {

    if (localStorage.token) {

        appendLogoutButtonToAuthButtons()
        changeVisibilityAuthButtons()
        changeBlackOutsDisplay()
        changeMyBtnVisibility()
        setCurrentUserVariables()
        fillOutPopUpOverallStats()
        fillOutPopUpOverallGames()
    }
    
}
})

Here, the document listens for DOMContentLoaded allowing me to check for the above condition before the DOM content was loaded (as the name implies). If the token exists in local storage, the user stays logged in, a logout button is appended, the game blackout is lifted and so on. This was vital for increasing the user experience. If the user walked away, or refreshed the page, the user should stay logged in with the ability to play the game. These are just a few tasty-tidbits of JavaScript code throughout Type Your Shark that demonstrate working with asynchronous behavior.


要查看或添加评论,请登录

社区洞察

其他会员也浏览了