Await inside JavaScript template strings

noseratio

Andrew Nosenko

Posted on June 2, 2021

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.

💖 💪 🙅 🚩
noseratio
Andrew Nosenko

Posted on June 2, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related