JS offers two ways of doing this: `Promise.then()` uses the callback style syntax. Much like an even

JS offers two ways of doing this:
Promise.then()
uses the callback style syntax. Much like an event handler, you pass
then()
a function, and JS will call that function only once the Promise is fulfilled - it won't call
prepGameSession()
until the package with the book in it is delivered. Often, multiple Promises are chained together, with each
.then()
returning another Promise.
function beGM() {
  orderBook()  // The promise fullfills when the order is delivered
    .then((book) => prepGameSession(book))
    .then((session) => playTTRPG(session));
}

The other, somewhat more straightforward but often more mysterious method is
async
and
await
. The more important keyword here is
await
it means "stop here until the next thing is done." When you use this method, it's a bit more clear what you are doing, though it introduces a quirk: You can't
await
if your function isn't
async
, and the return value of an
async
function is always a Promise - this can cause some confusion, and a cascade of refactoring as many methods get converted to
async
in an attempt to make things work as expected.
async function beGM() {
  const book = await orderBook();
  const session = await prepGameSession(book);
  playTTRPG(session);
}
Was this page helpful?