FRONTENDO
Emberhold Forge
0
0
APIs & Async · Async / Await
New technique

Promises, in plain words

Same promises underneath, but now the code reads like a story, top to bottom.

async/await is syntax built on top of promises. It does the same work as a .then chain, but reads like ordinary code: one line after another, with normal variables in between.

You mark a function with async. Inside it, await in front of a promise pauses the function until the promise settles, then hands you its value. While it's paused, the rest of the page keeps running: nothing is blocked.

// With .then
function nameWithThen() {
  return fetch("/api/swords/7")
    .then((res) => res.json())
    .then((sword) => sword.name);
}

// With async/await: the same thing
async function nameWithAwait() {
  const res = await fetch("/api/swords/7");
  const sword = await res.json();
  return sword.name;
}
  • An async function always returns a promise. Return 5, and callers get a promise of 5, so they need await (or .then) to get the 5 itself.