MT IT
  • Introduction
  • KEEP IN MIND!!
  • 1️⃣1st month
    • Week 1
      • HTML/CSS
        • HTML
          • HTML Dasar
          • HTML Layouting
          • Learn More
            • Semantic HTML
            • Tables
            • Videos
            • Images
        • CSS
          • CSS Dasar
      • Weekly Review
    • Week 2
      • Bootstrap
        • Tutorial Bootstrap 5
      • Git & Github
      • Responsive
        • Responsive with Bootstrap 5
      • Weekly Review
    • Week 3
      • Javascript
        • Introduction to Javascript
          • What is JavaScript?
          • Brief History of JavaScript
          • How To Add JavaScript to HTML
        • All About Variables
          • Variables
          • Naming JavaScript Variables
          • JavaScript Naming Conventions
          • JavaScript Scope
        • Datatypes
          • What are data types?
          • Primitives and objects
          • Primitive data types
          • Object data types
          • TypeOf Operator
      • Weekly Review
    • Week 4
      • Javascript
        • Data Structures
          • Keyed Collections
          • Indexed collections
        • Equality Comparisons
        • Loops and Iterations
          • The for loop
          • do…while statement
          • while statement
      • Weekly Review
    • Monthly Review
  • 2️⃣2nd Month
    • Week 5
      • Javascript
        • Expressions and Operators
          • Basic operators, maths
          • Assignment operators
          • Comparison operators
          • Logical operators
          • String operators
          • Conditional (ternary) operator
          • Comma operator
        • JavaScript Function
        • Arrow function expressions
        • Built in functions
      • REST - Representational State Transfer
        • API - Application Programming Interface
        • Fetching data from the server
        • The Fetch API
        • Cross-Origin Resource Sharing (CORS)
      • Weekly Review
    • Week 6
      • DOM (Document Object Model)
        • DOM tree
        • Selecting elements
          • getElementById()
          • getElementsByName()
          • querySelector()
        • Manipulating elements
          • createElement()
          • appendChild()
          • textContent
        • Working with Attributes
          • Understanding Relationships Between HTML Attributes & DOM Object’s Properties
          • setAttribute()
          • getAttribute()
          • removeAttribute()
          • hasAttribute()
        • Manipulating Element’s Styles
          • JavaScript Style
          • getComputedStyle()
          • className
          • classList
          • Getting the Width and Height of an Element
        • Working with Events
          • JavaScript Events
          • Handling Events
          • Page Load Events
          • onload
          • Mouse Events
          • Keyboard Events
          • Scroll Events
          • scrollIntoView
      • React JS
        • Getting Started
        • Components Basics
          • Introducing JSX
          • Writing Markup with JSX
          • React Function Components
          • Props vs State
            • State: A Component's Memory
            • How to use Props in React
      • Working with APIs - 1
        • XMLHttpRequest
        • Fetch
      • Weekly Review
    • Week 7
      • Javascript
        • Asynchronous JavaScript
          • Asynchronous JavaScript For Dummies
            • (Pt1): Internals Disclosed!
            • (Pt2): Callbacks
            • (Pt3): Promises
            • (Pt4): Async/Await
        • Callback
        • Promises
          • Promises Basics
          • Promises Chaining
          • Promises Error Handling
        • Async/await
          • async function
        • Tutorial – Learn Callbacks, Promises, & Async/Await in JS by Making Ice Cream
      • React JS
        • Rendering
          • Conditional Rendering
          • Lists and Keys
          • Render Props
        • Hooks
          • useState
          • useEffect
      • Working with APIs - 2
        • Axios
      • React Router Dom
      • Weekly Review
    • Week 8
      • React JS
      • Responsive
      • Chakra UI
      • Firebase
        • Firebase Authentication
      • Weekly Review
    • Monthly Review
  • 3️⃣3rd month
    • Week 9
      • React JS
      • Chakra UI
      • Firebase
      • Axios
      • Weekly Review
    • Week 10
      • React JS
      • Boilerplate
      • Weekly Review
    • Week 11
      • Projects
      • Weekly Review
    • Week 12
      • Projects
      • Weekly Review
    • Project Review
  • 🏁FINAL REVIEW
  • 👇!! Learn More Below !!
  • 🥸Frontend Stack
    • 💻Web Dev
      • React JS
        • Reactstrap
        • React Icons
        • React Router Dom
      • Chakra UI
    • 📱Mobile Dev
      • React Native
        • Introduction
        • Page 1
      • Expo
      • Nativebase
    • 🎽CSS
      • Tailwind
      • Bootstrap
  • ☕Backend Stack
    • Node JS
    • Firebase
      • Authentication
      • Firestore
      • Storage
      • Hosting
      • Cloud Function
      • Emulators
      • RTDB
      • FCM
    • Google Cloud Platform
      • AppEngine
      • Big Query
      • Cloud Functions
      • Cloud Run
      • Cloud Scheduler
      • Cloud SQL
      • Logging
    • Object Relational Mapping (ORM)
      • Sequelize
    • MongoDB
      • MongoDB Realm
    • MySQL
      • Introduction
  • 🦸Fullstack
    • NEXT JS
    • LARAVEL
  • 📦Package
    • Middleware
      • Express JS
    • HTTP client
      • AXIOS
    • 📊Chart
      • Chart.js
      • JSCharting
      • React Google Chart
    • ⏳Date & Time
      • Moment JS
      • Day JS
    • 👨‍💻WYSIWYG Editor
      • Quill JS
      • Slate JS
Powered by GitBook
On this page
  • async/await: Who am I?
  • async/await: How?
  • async/await: Why?
  1. 2nd Month
  2. Week 7
  3. Javascript
  4. Asynchronous JavaScript
  5. Asynchronous JavaScript For Dummies

(Pt4): Async/Await

Previous(Pt3): PromisesNextCallback

Last updated 1 year ago

this final part of the Asynchronous JavaScript For Dummies series, we’re going to see the async/await feature in JavaScript. And as usual, by the end of this tutorial, I hope, you’ll have a good understanding of the what, the how, and the why of async/await.

async/await: Who am I?

Simply put, async/await is just another way to write a code. It is a kind of sugar syntax for promises in JavaScript. This feature has been introduced in the ES8 version of JavaScript.

async/await: How?

As you might have already noticed, the name of this feature is composed of two main keywords, the “async” keyword, and the “await” keyword. Let’s elaborate on each one of them separately.

# async…

Let’s have a look at this piece of code,

I want you to understand three things If you see the async keyword. When the JavaScript engine hits the async keyword,

  • It is going to expect that the function that follows is going to hold some asynchronous code within it.

  • It is going to expect that the function will explicitly return a .

  • If not, it will implicitly return a promise for you wrapping the returned value of the function.

If you do try the example above on your end, you’ll see something like the following printed to the console,

Notice that even though, we did not explicitly return a promise, a fulfilled promise with the value ‘1’ is returned implicitly.

# await…

When we said that an async function is expecting an asynchronous code, we meant having “await expressions” within its body.

What the await keyword tells the JavaScript engine when it hist it is,

Please, come back when the promise I am handling will be settled ( fulfilled or rejected). Meanwhile, you can keep up working outside the function. Thanks.

You should notice also that the await operator will always return the value with which the promise has been settled (any value or a reason).

If we run the code sample above, we’ll get,

Even though we invoked the function p() first, ‘Some synchronous code…(outside)’ got printed before ‘1’. This explains what we’ve been talking about a while ago. The synchronous code outside the async function gets run first, and then when the await expression is ready, we come back to it and finish what is remaining within the async function. In our case, it is printing the value of result which holds the value ‘1’ at this point in time.

One more last thing to add, the code that comes before the very first await expression within an async function always runs synchronously. This is why, in our example, we’re getting ‘Some synchronous code…(inside)’ printed first.

async/await: Why?

There are two main benefits of using async/await in JavaScript…

# A Much Cleaner Code

If you’ve ever read the previous part of this tutorial,

We talked about the concept of “chaining”. What the async/await feature does is increase the readability of our code. It hides the chain for us. Our code would feel synchronous, while it is still asynchronous underneath.

Let’s replicate the same promises-based example we had in the previous part of this tutorial and write it again with the async/await syntax.

Try this code, I promise, you’ll get the same output as the promises-based one. But this time the code looks cleaner and simpler, isn’t it?

# A Better Error Handling

If we intentionally through an error in the code above, we can still get it this way,

Because remember, an async function implicitly returns a promise for you. Therefore, we can make use of the catch() method to catch any errors within the function as illustrated in the above example.

The output would always be the same with both ways,

How cool is that?

That’s it. We are at the end of the Asynchronous JavaScript For Dummies tutorial. Hopefully, now, you can use asynchronous programming in your future projects with ease.

Till next time, enjoy learning :)

Now, the thing is you can be flexible, you could use another way to catch errors through the structure,

2️⃣
Asynchronous JavaScript For Dummies(Pt3): PromisesYou’ll learn about promises in JavaScript. Unlock the what, the how and the why of promises.medium.com
try/catch
promises-based
promise