28

Why won't the following snippet work here on Stack Overflow?

I'm trying to add some example of basic async/await and returned promises.

This exact same piece of code works just fine on my development environment. I'm using Babel, but I've seen snippets with async await functions here on Stack Overflow before.

What's happening?

It gives the error:

{
  "message": "Script error.",
  "filename": "",
  "lineno": 0,
  "colno": 0
}

function bar() {
  return new Promise((resolve,reject) => {
    setTimeout(()=> {
      resolve('resolved after 1500ms');
    },1500);
    // return resolve('resolved');
  });
}

async function foo() {
  const result = await bar();
  console.log(result);
}

foo();

I'm on Chrome version 75.0.3770.80 (official build) (64-bit).

4

1 Answer 1

35

Update: This is fixed as of Oct 3 2024, see the updates in this bug report (which SE called a "feature request").


The problem is that the version of babel-standalone used by Stack Snippets is (well) out of date and doesn't understand async/await. Amusingly, on any modern browser, if you untick the Babel box in the snippet, it'll work. But if you want JSX compilation, you need to tick the box, so using async in (say) a React question won't work.

It also works if you use a current version of babel-standalone, like this:

<script src="https://unpkg.com/@babel/standalone@7/babel.min.js"></script>
<script type="text/babel">
function bar() {
  return new Promise((resolve,reject) => {
    setTimeout(()=> {
      resolve('resolved after 1500ms');
    },1500);
    // return resolve('resolved');
  });
}

async function foo() {
  const result = await bar();
  console.log(result);
}

foo();
</script>

Note that you can't put the code that Babel will process in the JavaScript panel in the snippet editor. You have to put it in the HTML panel instead, in a <script type="text/babel">...</script> tag.

4
  • @3limin4t0r - Thanks for updating the version. FWIW, it doesn't matter where the Babel script is. It uses a DOMContentLoaded handler to look for scripts to handle. For me it made more sense to put it at the end, but it doesn't matter. :-) Commented Mar 1, 2021 at 12:13
  • In most cases the external scripts will be at the top of the snippet, so I thought it would be better located at the top. But it indeed doesn't really matter if it's at the top or bottom.
    – 3limin4t0r
    Commented Mar 1, 2021 at 12:18
  • 3
    @3limin4t0r - Yeah. Putting scripts at the top is a bit of an anti-pattern, I wish the snippet editor didn't do that. :-) (But they've always ignored my offers to improve Stack Snippets for them, for free. Sigh.) Commented Mar 1, 2021 at 12:21
  • (Without defer, that is. :-) ) Commented Mar 1, 2021 at 12:34

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .