This page looks best with JavaScript enabled

Use await without async function in Javascript

 ·   ·  ☕ 1 min read

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..

1
2
3
4
5
6
7

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).

1
2
3
4
5
6
7
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!

Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things