</> Code Corner

JavaScript · JS Async · Lesson 53

JS Async/Await

Write promise-based code that reads like synchronous code.

async makes a function return a Promise. await makes a function wait for a Promise.

Example

<p id="demo">Loading...</p>
<script>
function wait(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}
async function loadData() {
  try {
    await wait(800);
    const step1 = "Step 1 done";
    await wait(800);
    document.getElementById("demo").innerHTML = step1 + "<br>Step 2 done";
  } catch (error) {
    document.getElementById("demo").innerHTML = "Error: " + error;
  }
}
loadData();
</script>
Tip: await can only be used inside an async function (or at the top level of a module). Use try...catch to handle errors.

Keep reading “JS Async/Await”

Sign up to read the full lesson, try every example in the live editor, and take the 5-question quiz.

Chat with us 👋