How to Use Async/Await in JavaScript: A Practical Keyboard Event Example

4. Async/Await for Cleaner Asynchronous Code

Async/await is syntactic sugar built on top of Promises. It allows you to write asynchronous code that looks and behaves like synchronous code, making it much easier to read and debug.

To demonstrate this, let's create a small interactive demo: when the user presses the Enter key, a message appears. Then, only when the user presses the Spacebar, a second message appears. We'll use async/await to manage this sequence clearly.

🔧 Code Example:


// Wait for a specific key to be pressed
function waitForKey(keyName) {
  return new Promise(resolve => {
    function handler(event) {
      if (event.key === keyName) {
        document.removeEventListener('keydown', handler);
        resolve();
      }
    }
    document.addEventListener('keydown', handler);
  });
}

async function runSequence() {
  const output = document.getElementById('output');
  output.innerHTML = 'Waiting for Enter key...';

  await waitForKey('Enter');
  output.innerHTML = 'Enter pressed! Now press Space...';

  await waitForKey(' ');
  output.innerHTML = 'Spacebar pressed! Sequence complete ✅';
}

runSequence();

🔍 Live Demo:

Press the Enter key to start...

Why this matters: Without async/await, this sequence would be much harder to manage and could easily become a messy chain of callbacks. With async/await, the code reads top-down and is easier to follow and maintain.

Comments

Popular posts from this blog

Do You Really Need Advanced Algorithms to Be a Great Developer in 2025?

Advanced Chrome Dino Game (HTML + JS + Sprites)

Boost Productivity Using AI and REST APIs