DEV Community

Tinkerjoe-Git
Tinkerjoe-Git

Posted on

Why we use JS's Async functions.

An Asynch function is a function declared with the async declaration keyword.

Another keyword often used in tandem with async is await which enables asynchronous promises to be written more simply by avoiding the explicit coding of a promise chain.

before going any further, why are we interested in asynchronous JS anyways?

To get to where we're going we have to understand Javascript is a single threaded language - which means exactly it can execute one piece of code at a time - that's it. When we're doing things synchronously each process must complete and everything else gets blocked or essentially queued up until we can move past the current line of code being completed...seriously? seriously

Given the perceived demands and complexity of modern applications / browsers, users aren't going to simply wait around for your bulky code to execute. Think about image rendering for instance, this is paused until the stack is cleared and resolved essentially.

Asynchronous JS

To avoid the aforementioned 'blocking' we use async callbacks, which will start executing in the background, when its finished running the callback is called.

btn.addEventListener('click', () => {
  alert('You clicked me!');
Enter fullscreen mode Exit fullscreen mode

the second param () is the callback function once the click is heard. The code above is arguably a more 'dated' way to be writing async code, I wouldn't be doing flatiron any justice if I didn't show you the worse way to do things first ^_^.

Promises

Promises are the 'newer' more modernized async code. For my project I'm grabbing 'card/deck' data from my API.

    getDecks(){

        fetch(this.baseDeckURL)
        .then(r => r.json())
        .then(decks => {
            decks.forEach(deck => {
                const d = new Deck(deck)
                d.addToDom()
            })
        })
        .catch(err => console.warn(err))
    }
Enter fullscreen mode Exit fullscreen mode

fetch is taking in a single URL param, and returning a promise.
The promise being an object which represents the (ideal) completion or perhaps failure of the async operation. Now, the fetch does technically have to await the result of our browser to complete the function like anything else. Essentially the queuing of the event allows the main code to finish so as to not block any further events. The name of the game here is to have your user experience be a smooth one, as opposed to being bogged down by code running and fetching, waiting for downloads and so on. In these simple terms we can understand the purpose of wanting to code our JS functions asynchronously.

Top comments (0)