DEV Community

Andrew Nosenko
Andrew Nosenko

Posted on • Edited on

Await inside JavaScript template strings

Did you know it is possible to use await inside interpolated JavaScript template strings (aka template literals)? I personally did not, and have just discovered that by an accident.

For example, try this with Node or Deno (runkit and gist; save the code as .mjs so it runs as an ESM module):

const delay = (ms, result) => 
  new Promise(r => setTimeout(r, ms, result));

const interpolated = `Hello, ${await delay(1000, "World!")}`; 

console.log(interpolated);
Enter fullscreen mode Exit fullscreen mode

This code works in the browser console as well, verified for Chrome/Edge/Firefox.

It does require the top-level await support, or otherwise has to reside inside an async function, as it's basically just a syntactic sugar for:

const interpolated = "Hello, " + await delay(1000, "World!");
Enter fullscreen mode Exit fullscreen mode

Why would this feature be useful? For one thing, I can think of a poor man's text templating engine for JavaScript, where instead of delay we might be using something like fetch, readFile or any other Promise-based APIs.

For now, I've added this to my collection of a few handy JavaScript tricks.

Updated, here's a follow-up article: Automation with Deno: a tiny text template processor in JavaScript.

Top comments (2)

Collapse
 
brancualexandru profile image
Brancu Alexandru • Edited

That is super interesting! I just found this out, while learning how to use async ... await in codeacademy!! Unfortunately their compiler doesn't let this work for some reason.

EDIT: I literally spelled a var name wrong, it works perfectly. But it's not accepting my solution as valid because reasons.
:/

Collapse
 
noseratio profile image
Andrew Nosenko

Not all online IDEs support top level await, but you can wrap it as an async function.