DEV Community

loading...

Await inside JavaScript template strings

Andrew Nosenko
Dad, self-employed, problem solver at heart, async all the way. Formerly a principal software engineer at Nuance Communications. Occasionally I tweet, blog and answer my own StackOverflow questions.
Updated on ・1 min read

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.

Discussion (0)