Use await without async function in Javascript

How can you use await without an async function? Don’t click or proceed further if you are not into practical jokes.

Say, you try using await in a “normal” function or directly within a module..

function getWeather(loc) {
    const weather = await fetchWeather(loc);
    return weather;

// SyntaxError: await is only valid in async function

You receive a compilation error that await can be used only in async function.

But, if I have to use await but do not want to create a separate function with its own memory space, what should I do?

This question actually finds its place in the pre-defined set of interview questions from a particularly bad interviewer. So, the answer can be equally bad.

Use an ‘immediately invoked function expression’ (IIFE).

function getWeather(loc) {
  (async function() {
    const weather = await fetchWeather(loc);

  // on and on - code with no dependency on weather

If you are thinking by now that the whole ‘await w/o async’ thing is not really a joke, but a joke of a post - you may be absolutely right!

comments powered by Disqus