-2
async function checkStatus() {
  const data = await fetch();

  return data.json();
}

const result = checkStatus() // Promise

How can I make something like await for response from checkStatus() outside of the function. As I understand it isn't possible to make:

const result = await checkStatus()

But how can I make something similar ?

Andrey Radkevich
  • 3,012
  • 5
  • 25
  • 57

2 Answers2

1

There are some environments that support "top-level await" so const result = await checkStatus() would actually work.

In environments that don't support top-level await, you can wrap your whole const result = await checkStatus() inside an immediately invoked function expression (IIFE) as follows (note the function is an async one).

async function checkStatus() {
  const data = await fetch();

  return data.json();
}

(async () => {
  const result = await checkStatus();
})();

Alternatively you can just use the Promise API:

checkStatus().then(result => {
  // do stuff with result
});
Hugo
  • 3,500
  • 1
  • 14
  • 28
0

You can wrap your code inside an async function:

(async () => {
  const result = await checkStatus();
  // ...
})();

Or use .then():

checkStatus().then(result => {
  // ...
});
D. Pardal
  • 6,173
  • 1
  • 17
  • 37